Auto login

starlitxiling Lv3

应该有很多学校的校园网都是需要登录才能使用的,然后在我们学校,这种登录机制,不知道为什么有时候会莫名其妙掉出来,需要重新登录。这样就很麻烦,所以自己写了一个自动登录的脚本,能够在断开的时候自动重新登录。

以下代码里的所有参数都请以浏览器中抓取的包为准!!!示例仅供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import requests
import time
import logging
import subprocess

logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)

login_url = "http://10.17.8.18:801/eportal/portal/login" # 这是登录页面的链接,要以包里提供的为准
login_data = {
'callback': 'dr1003',
'login_method': '1',
'user_account': '@telecom', # 这里@符号前填账号,telecom表示电信,移动是cmcc,联通是unicom
'user_password': '' , # 这里是密码
'wlan_user_ip': '',
'wlan_user_ipv6': '',
'wlan_user_mac': '',
'wlan_ac_ip': '',
'wlan_ac_name': '',
'jsVersion': '4.1.3',
'terminal_type': '1',
'lang': 'en',
'v': ''
}

headers = {
'User-Agent': '', #UA
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Cookie': '' #这里不要也没关系
}

def login(session):
logging.info("网络断开,尝试重新登录!")
response = session.get(login_url, params=login_data, headers=headers)
return response.ok

def is_network_available():
try:
response = requests.get("https://www.google.com/generate_204", timeout=5)
# response = requests.get("http://detectportal.firefox.com/success.txt", timeout=5)

if response.status_code == 204:
return True
except requests.RequestException:
pass

try:
result = subprocess.run(["ping", "-n", "1", "-w", "3000", "8.8.8.8"], capture_output=True, text=True, encoding="gbk", errors="ignore") # Windows下需要指定gbk编码
if "TTL=" in result.stdout:
return True
except Exception as e:
logging.error(f"Ping 检测失败: {e}")

return False

def check_network(session):
if is_network_available():
return True

if login(session):
logging.info("登录成功")
return False
else:
return False

def monitor():
with requests.Session() as session:
while True:
check_network(session)
time.sleep(5)

monitor()

这里比较难发现的是第40行这个代码,我起初在mac下使用baidu.com是可以正常检测网络是否正常连接的,但是在Windows下,它会被重定向到登录页,然后会导致判断错误(就是检测到联网了但实际上并没有)。这来源于Windows会对HTTP请求进行重定向,但不会对HTTPS进行劫持,所以我们可以使用https://www.google.com/generate_204http://detectportal.firefox.com/success.txt,后者有时候也会出错,建议使用前者。当然也可以直接忽略这个,直接用下面的ping逻辑。
如果你的校园网为post请求,你就需要将第35行的代码改为session.post(login_url, data=login_data)。相关的参数为:

1
2
3
4
5
login_url = "登录页面的URL"
login_data = {
'username': '', # 用户名
'password': '', # 密码
}
  • Title: Auto login
  • Author: starlitxiling
  • Created at : 2025-02-17 19:02:39
  • Updated at : 2025-02-17 20:22:14
  • Link: http://starlitxiling.github.io/2025/02/17/Auto-login/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Auto login