此方法适用于通过路由器拨号上网的宽带,若宽带通过光猫拨号上网则需要将光猫改为桥接模式并在路由器中配置宽带账号和密码
测试环境:
路由器:TP-LINK TL-WDR7800千兆版
硬件版本:1.0
软件版本:1.0.2
路由器内网IP地址:192.168.0.1
一、准备
确保系统当中安装了python3,且在命令提示符中输入python --version返回的是python3而不是python2
使用pip install requests安装requests库
使用Chrome或Firefox自带的调试工具抓包,找到正常登录路由器时提交的密文
用密文替换python脚本中的xxxxxxxxxxxxxxx(密文长度介于15~32之间,以实际抓包结果为准)
用路由器的实际内网IP替换脚本中的192.168.0.1
二、使用
python脚本如下:
import requests,json
from time import sleep
routeurl = "http://192.168.0.1/"
ipurl = "https://jsonip.com/"
logindata = '''{"method":"do","login":{"password":"xxxxxxxxxxxxxxx"}}'''
command = '''{"network":{"change_wan_status":{"proto":"pppoe","operate":"disconnect"}},"method":"do"}'''
headers = {
"Content-Type":"application/json; charset=UTF-8",
}
state = 0
try:
res=requests.get(url=ipurl)
except BaseException as e:
print("Cannot connect to Internet.Exiting...")
sleep(3)
exit()
IP1=json.loads(res.text)["ip"]
print("Current IP is "+IP1)
while(state!=1):
print("Changing IP..."+"\n")
res=requests.post(url=routeurl,headers=headers,data=logindata)
if (res.status_code == 401) :
print("Password is incorrect. Exiting...")
break
'''print(res)'''
'''print(res.text)'''
token=json.loads(res.text)["stok"]
'''print(token)'''
res=requests.post(url=routeurl+"stok="+token+"/ds",headers=headers,data=command)
'''print(res)'''
'''print(res.text)'''
print("Command has been sent")
print("Waiting for Internet connection..."+"\n")
while True:
print("Connecting...")
try:
res=requests.get(url=ipurl,timeout=10)
except BaseException as e:
continue
break
print("Connected"+"\n")
IP2=json.loads(res.text)["ip"]
print("Current IP is "+IP2)
if (IP2 != IP1):
state = 1
print("\n"+"IP has changed")
else:
state = -1
print("\n"+"Failed. Retrying...")
print("------------")
sleep(3)
将以上内容保存为.py文件并通过python执行即可
若想直接运行,可新建一个.bat文件,输入以下内容并保存
@python "C:\1.py"
其中英文双引号之间的内容用.py文件的路径代替
之后双击该.bat文件即可
2019.08.22