如何用python脚本控制TPLINK路由器

2024-10-06 12:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一个工具允许我连接到路由器并关闭它,然后从python脚本重新启动它。

我知道如果我用python脚本编写:import os,然后执行os.system("ssh -l root 192.168.2.1"),我可以通过python连接到我的路由器。但是,我不知道如何应用路由器的密码,如何登录,以便重新启动它。

因此,在对其进行了一些研究之后,这里是我为使用python脚本通过SSH会话连接到路由器而编写的代码:

    import os, urllib, urllib2, re

    def InterfaceControl():
       #os.system("echo training")
       os.system("ssh -l root 192.168.2.1")
       os.system("echo yes")
       os.system("echo My_ROUTER_PASSWORD")
       os.system("shutdown -r")



     def main():
         InterfaceControl()


     if __name__=="__main__":
         main()

问题是我仍然无法用这段代码连接到路由器,而且IDLE(我用来编写和运行python脚本的编辑器)崩溃了。有谁能帮我改进这个代码吗?


Tags: 工具代码importecho脚本密码osmain
3条回答

这取决于您的tplink设备型号和固件,因为不同型号的auth算法不同。 我写了那个python脚本,它对我的tp链接W740N很好

#!/usr/bin/python3
# imports
from requests import get
from base64 import b64encode
from urllib.parse import quote


# constants
tplink = '192.168.0.1'
user = 'admin'
password = 'admin'
url_template = 'http://{}/userRpm/SysRebootRpm.htm?Reboot=Reboot'


if __name__ == '__main__':
    auth_bytes = bytes(user+':'+password, 'utf-8')
    auth_b64_bytes = b64encode(auth_bytes)
    auth_b64_str = str(auth_b64_bytes, 'utf-8')

    auth_str = quote('Basic {}'.format(auth_b64_str))

    auth = {
    'Referer': 'http://'+tplink+'/', 
    'Authorization': auth_str,
    }

    reboot_url = url_template.format(tplink)

    r = get(reboot_url, headers=auth)

我认为对于新的固件版本,您需要: referer和用户代理工作。

我想你可以看看路由器管理页面,看看它发送的post参数。在脚本中你可以模仿同样的内容。

我认为大多数路由器都使用基本的https认证。

编辑:找到了这个。

wget -qO- --user=admin --password=admin-password http://192.168.1.2/userRpm/SysRebootRpm.htm?Reboot=Reboot

src:http://blog.taragana.com/old-code-how-to-reboot-tp-link-router-11849

我的wget手册告诉我-q是用来安静的。不知道0是什么。你也可以用curl做类似的事情。 注意:一些tp链接设备要求发送referer头。例如在curl中,-H 'Referer: http://192.168.0.1'

我可以在python中使用下面的代码来完成同样的工作。

from urllib.request import urlopen, Request
import base64
req = Request('http://192.168.0.1/userRpm/SysRebootRpm.htm?Reboot=Reboot')
req.add_header('Authorization', ('Basic %s' % base64.b64encode('uname:pass'.encode('ascii')).decode('ascii')))
req.add_header('Referer', 'http://192.168.0.1')
urlopen(req)

相关问题 更多 >