我正在尝试编写一个Python脚本来升级我的路由器(TP-LINK)固件。
为了做到这一点,我从Admin Web界面升级了我的固件并用Wireshark嗅探它。然后我用Python构建了确切的POST请求,但由于某种原因它无法正常工作(我从路由器获得FIN)。
这是我的代码:
import httplib, mimetypes
fields = {"Upgrade":"Upgrade"}
files = {"Filename":"k.bin"}
uri = "/incoming/Firmware.htm"
host="Router's IP"
def post_multipart(host, uri, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTPConnection(host)
headers = {
'User-Agent': 'Mozilla/5.0 (Xll; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1',
'Content-Type': content_type,
'Authorization': 'Basic xxxxxxxxxxx=',
'Accept-Encoding': 'gzip, deflate',
'Connection':'keep-alive',
'Referer':'http://Routers IP/userRpm/SoftwareUpgradeRpm.htm',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'en-US,en;q=0.5'
}
h.request('POST', uri, body, headers)
res = h.getresponse()
return res.status, res.reason, res.read()
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '-----------------------------19933564951268966553507360333'
CRLF = '\r\n'
L = []
print "Uploading..."
for key, filename in files.items():
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(open("k.bin","rb").read())
for key, value in fields.items():
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
post_multipart(host, uri, fields, files)
非常感谢帮助!