用python实现自动重启tplink路由器
原因
自从我的iPhone升级到iOS16之后,总是连不上家里的5G WiFi。开始确实是因为iOS16的bug造成的,升级到最新iOS版本之后稳定了几天,但是之后就又出现了连不上的情况,不过我老婆的手机和iPad倒是挺正常的。最后祭出重启路由大招,完美解决问题。于是想着做个定时重启任务,结果在路由器里面没找到设定,于是只好自己动手,用python写了一个重启脚本。
代码
import requests
class TpLink:
"""tplink类"""
def __init__(self, ip: str, pwd: str):
self._strDe = b"RDpbLfCPsJZ7fiv"
self._dic = b"yLwVl0zKqws7LgKPRQ84Mdt708T1qQ3Ha7xv3H7NyU84p21BriUWBU43odz3iP4rBL3cD02KZciX" +\
b"TysVXiV8ngg6vL48rPJyAUw0HurW20xqxv9aYb4M9wK1Ae0wlro510qXeU07kV57fQMc8L6aLgML" +\
b"wygtc0F10a0Dg70TOoouyFhdysuRMO51yY5ZlOZZLEal1h0t9YQW0Ko7oBwmCAHoic4HYbUyVeU3" +\
b"sfQ1xtXcPcf1aT303wAQhv66qzW"
self.pwd = bytes(pwd, encoding="utf-8")
self.ip=ip
def password_encode(self):
dictionary = self._dic
output = ''
cl = 0xBB
cr = 0xBB
lenght1 = len(self.pwd)
lenght2 = len(self._strDe)
lenDict = len(dictionary)
lenght = lenght1 if lenght1 > lenght2 else lenght2
for index in range(lenght):
cl = 0xBB
cr = 0xBB
if index >= lenght1:
cr = self._strDe[index]
elif index >= lenght2:
cl = self.pwd[index]
else:
cl = self.pwd[index]
cr = self._strDe[index]
output += chr(dictionary[(cl ^ cr) % lenDict])
self.encoded_pwd = output
def login(self):
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh,en;q=0.9,zh-CN;q=0.8',
'Connection': 'keep-alive',
'Content-Type': 'application/json; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
json_data = {
'method': 'do',
'login': {
'password': self.encoded_pwd,
},
}
response = requests.post('http://{0}/'.format(self.ip),
headers=headers, json=json_data, verify=False)
j = response.json()
self.stok = j.get('stok')
print(response.status_code)
def reboot(self):
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh,en;q=0.9,zh-CN;q=0.8',
'Connection': 'keep-alive',
'Content-Type': 'application/json; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
json_data = {
'hyfi': {
'reboot_all': None,
},
'method': 'do',
}
response = requests.post(
'http://{0}/stok={1}/ds'.format(self.ip,self.stok),
headers=headers,
json=json_data,
verify=False,
)
print(response.status_code)
a = TpLink(ip="192.168.0.51",pwd="password")
a.password_encode()
a.login()
a.reboot()
结尾
这个代码其实很简单只需要通过浏览器控制台获取下登录和重启的参数和url,以及密码加密。如果你的路由器是tplink的,应该是可以直接用的。