0 省流
https://github.com/Cuiyingzhe/OUCNetworkAutoConnection/releases/tag/v2.0
下载yxrz.exe
执行即可
1 问题描述
海大校园网(办公室有线网络)使用网页账号密码认证进行登录,总是时不时断网,导致向日葵无法连接到服务器。受https://zhuanlan.zhihu.com/p/370801224启发,基于python实现自动监测校园网连接状态,发现断网情况后发送请求自动重新连接到校园网。
注:只针对网线连接正常但经常突然登出的情况,若网线硬件、电脑死机蓝屏等问题导致无法联网则不能通过此方法解决。
2 监测校园网连接状况
由于后面断网提交连接请求是基于python的requests库,这里监测连接状况就也是用python调用Windows系统的curl命令来实现。(我看很多帖子使用ping也是可以的,但是比curl要稍慢一点)
from subprocess import run, PIPE
import requests
import time
while True:
r = run('curl www.baidu.com',
stdout=PIPE,
stderr=PIPE,
stdin=PIPE,
shell=True)
if len(str(r.stdout, 'UTF-8'))==0:
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+' 正在重新连接')
login(oucid, pwd)
else:
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+' 连接成功')
time.sleep(1) #单位 s
其中login()
是我们下面要实现的重连函数
网络连通时,curl www.baidu.com
输出:
无法连通时则为空白输出。因此利用该命令的输出字符串长度来判断网络是否连通。
下面实现login()
函数。
3 提交连接请求
def login(oucid, pwd):
url = 'https://yxrz.ouc.edu.cn'
data = {
"DDDDD": oucid, # 学号
"upass": pwd, # 校园网密码
"R1": "0",
"R3": "0",
"R6": "0",
"para": "00",
"0MKKey": "123456",
}
header = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN ,zh;q=0.9",
"Connectin": "keep-alive",
"Host": "https://yxrz.ouc.edu.cn",
"Referer": "https://yxrz.ouc.edu.cn/a79.htm",
"sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"Sec-Fetch-Dest": "script",
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36",
}
response = requests.post(url, data, headers=header).status_code
print("返回代码{}".format(response))
代码中的信息来自登录校园网时浏览器发送的请求(Request URL
和Request Headers
:
4 打包为可执行文件
pyinstaller -F -p 'D:\\Anaconda\\lib\\site-packages' yxrz.py
打包为可执行文件,以后运行该可执行文件即可。