如何使用 python 脚本控制 TPLINK 路由器 [英] How to control a TPLINK router with a python script

查看:102
本文介绍了如何使用 python 脚本控制 TPLINK 路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to know whether there is a tool that allows me to connect to a router and shut it down, and then reboot it from a python script.

我知道如果我写:

import os
os.system("ssh -l root 192.168.2.1")

我可以通过 python 连接到我的路由器.但是,我不知道如何应用路由器的密码,并登录它以重新启动它.

I can connect through python to my router. But then, I don't know how to apply the router's password, and to log into it, in order to reboot it.

因此,在稍微处理一下之后,这里是我编写的代码,以便使用 python 脚本通过 SSH 会话连接到我的路由器:

So after working on it a bit here is the code that I have written in order to connect to my router with an SSH session using a python script:

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 脚本的编辑器)崩溃了.谁能帮我改进这段代码?

The problem is that I still can't connect to my router with this code, and moreover, IDLE (the editor I use for python scripts) crashes. Can anyone help me improve this code?

推荐答案

这取决于您的 tplink 设备型号和固件,因为认证算法因型号而异.

It depends on your tplink device model and firmware, because auth algorithm differ from model to model.

我编写了这个 python 脚本,它适用于我的 tp 链接 W740N.该代码解释了如何使用请求包在此设备上进行身份验证

I wrote this python script which works fine for my tp link W740N. The code explains how to authenticate on this device using requests package

#!/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)

这篇关于如何使用 python 脚本控制 TPLINK 路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆