Skip to content

Instantly share code, notes, and snippets.

@LiZeC123
Created July 25, 2021 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LiZeC123/80d95703ae81cc111fa063c4fdd5a815 to your computer and use it in GitHub Desktop.
Save LiZeC123/80d95703ae81cc111fa063c4fdd5a815 to your computer and use it in GitHub Desktop.
Requests库应用举例(重启路由器)
import requests
import time
import re
def get_cookie():
print("尝试获取授权码")
URL = "http://192.168.1.1/cgi-bin/luci"
HEADER = {
"Referer": "http://192.168.1.1/cgi-bin/luci/",
"Origin": "http://192.168.1.1",
"Content-type": "application/x-www-form-urlencoded",
"Host": "192.168.1.1",
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Mobile Safari/537.36",
}
PARAMS = {
"username": "useradmin",
"psd": "xdrxu"
}
r = requests.post(URL, headers=HEADER, params=PARAMS,
allow_redirects=False)
cookie = requests.utils.dict_from_cookiejar(r.cookies)
print(f"获得授权码为: {cookie.get('sysauth')}")
return f"sysauth={cookie.get('sysauth')}"
p = re.compile(r"token: '(.+?)'")
def get_token(cookie):
print("尝试获取token")
URL = "http://192.168.1.1/cgi-bin/luci/"
HEADER = {
"Referer": "http://192.168.1.1/cgi-bin/luci/",
"Origin": "http://192.168.1.1",
"Content-type": "application/x-www-form-urlencoded",
"Host": "192.168.1.1",
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Mobile Safari/537.36",
"Cookie": cookie
}
r = requests.post(URL, headers=HEADER)
token = p.search(r.text).group(1)
print(f"获得Token值为{token}")
return token
def post_reboot(cookie, token):
print("发送重启指令")
URL_REBOT = "http://192.168.1.1/cgi-bin/luci/admin/reboot"
HEAD_REBOT = {
"Referer": "http://192.168.1.1/cgi-bin/luci/",
"Origin": "http://192.168.1.1",
"Content-type": "application/x-www-form-urlencoded",
"Host": "192.168.1.1",
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Mobile Safari/537.36",
"Cookie": cookie
}
PARAMS = {
"token": token
}
bot_r = requests.post(URL_REBOT, headers=HEAD_REBOT, params=PARAMS)
print(f"重启指令返回码: {bot_r.status_code}")
def has_network():
try:
URL = "http://www.baidu.com"
r = requests.get(URL)
return r.status_code == 200
except BaseException:
return False
if __name__ == "__main__":
cookie = get_cookie()
token = get_token(cookie)
post_reboot(cookie, token)
print("1分钟后检查网络状态")
time.sleep(60)
while not has_network():
print("网络无法连接, 5秒钟后重试...")
time.sleep(5)
else:
print("网络恢复正常")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment