使用python请求将文件发布到我的Tp链接路由器
我正在尝试编写一个Python脚本来升级路由器的TP-LINK固件 为了做到这一点,我从管理web界面升级了固件,并用Wireshark嗅探它。然后,我用Python构建了确切的POST请求,但由于某些原因,它无法工作,我从路由器获得了FIN 这是我的代码:使用python请求将文件发布到我的Tp链接路由器,python,post,router,Python,Post,Router,我正在尝试编写一个Python脚本来升级路由器的TP-LINK固件 为了做到这一点,我从管理web界面升级了固件,并用Wireshark嗅探它。然后,我用Python构建了确切的POST请求,但由于某些原因,它无法工作,我从路由器获得了FIN 这是我的代码: import httplib, mimetypes fields = {"Upgrade":"Upgrade"} files = {"Filename":"k.bin"} uri = "/incoming/Firmware.htm" ho
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)
非常感谢您的帮助 通常,您必须重新启动路由器以查看升级的更改。您发布的代码没有重新启动路由器。您是否手动重新启动路由器并检查其是否未升级?谢谢您的帮助。路由器应在升级后重新启动。手动重新启动没有帮助。手动或自动重新启动路由器并不重要,如果固件上载成功,它将更新路由器的固件。关于重新启动问题,您只需在手动重新启动路由器时使用wireshark嗅探post请求,为重新启动创建另一个post请求,就像您在上载固件时所做的那样。我不能测试你的代码,因为我没有像你这样的路由器。我用串口连接到路由器,所以我可以看到固件没有升级…幸运的话@user3560554