python post传输文件脚本
ps:背景,无法ssh相互访问机器(一般中间有堡垒机阻拦)的情况下,但是使用域名可以进行访问的情况下 可以使用Http协议进行文件的上传。
服务器端代码(接受post的一端)
#coding=utf-8
from Basehttpserver import BaseHTTPRequestHandler
import cgi
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
fORM = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}
)
self.send_response(200)
self.end_headers()
self.wfile.write('Client: %sn ' % str(self.client_address) )
self.wfile.write('User-agent: %sn' % str(self.headers['user-agent']))
self.wfile.write('Path: %sn'%self.path)
self.wfile.write('Form data:n')
for field in form.keys():
field_item = form[field]
filename = field_item.filename
filevalue = field_item.value
filesize = len(filevalue)#文件大小(字节)
print len(filevalue)
with open(filename.decode('utf-8')+'a','wb') as f:
f.write(filevalue)
return
if __name__=='__main__':
from BaseHTTPServer import HTTPServer
sever = HTTPServer(('0.0.0.0',8000),PostHandler)
print 'Starting server, use <Ctrl-C> to stop'
sever.serve_forever()
客户端 (发送post的一端)
#coding=utf-8
import requests
url = 'http://xxxxxxxxxxxxxxxxxxx:8000'
path = u'/Users/test/student/py/myspider.py'
print path
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
相关文章