目录

锐捷校园网认证脚本

# 锐捷校园网认证脚本

可以把这个脚本写入定时任务里,每分钟通过访问百度页面,判断是否掉线并重连。

环境

python3 python requests库

安装requests库

pip install requests
1

自用脚本,看起来好像还是很臃肿

import re
import time
import random
import requests
from datetime import datetime

# 请求头部
headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Mobile Safari/537.36',
}
session = requests.Session()
def log_message(message):
    """记录日志"""
    with open("./auto-link-wifi.log", "a") as file:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        file.write(f"[{now}] {message}\n")
    print(message)

def is_network_available():
    """检测网络是否可用"""
    urls = {"http://baidu.com":"百度一下","https://aliyun.com":"阿里云","https://cloud.tencent.com/":"腾讯云","https://www.jd.com/":"京东","https://www.taobao.com/":"淘宝","https://y.qq.com/":"QQ音乐","https://music.163.com/":"网易云","https://www.tmall.com/":"天猫","https://www.163.com/":"网易","https://www.speedtest.cn/?from=itab":"测速网","https://www.doubao.com/":"豆包"}
    
    random_url = random.choice(list(urls.keys()))
    site_name = urls[random_url]
    try:
        response = session.get(random_url, timeout=10, headers=headers)
        return site_name in response.text
    except Exception as e:
        print(f"[-]:{e}")
        return False

def get_redirect_url():
    """通过访问百度域名,在跳转页面js获取参数"""
    test_url = 'http://baidu.com'

    response = session.get(test_url, timeout=10, headers=headers)
    if "百度一下" in response.text:
        message = f"✅[+]{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:当前网络可用,无需再次认证!"
        print(message)
        return None
    # 检查校园网解析到的网页,匹配网页js将要跳转的页面,即认证页面
    js_redirect = re.search(r'self\.location\.href\s*=\s*["\'](.*?)["\']', response.text)
    if js_redirect:
        return js_redirect.group(1)
    else:
        message = "❌:get_redirect_url()函数在定位校园网认证页面阶段,未能够获取js跳转参数......"
        log_message(message)
        return None

def auto_link_wifi(url, data):
    """自动认证"""
    resp = session.post(url, headers=headers, data=data)
    res_message = ""
    if resp.status_code == 200:
        if "success" in resp.text:
            res_message = "✅:认证成功,成功连接校园网"
        elif "fail" in resp.text:
            res_message = "❌:认证失败,请检查账号密码是否正确"
        print(res_message)
    else:
        res_message = "❌:脚本可能不适配当前认证系统"
    log_message(res_message)

if __name__ == "__main__":
    """账号、密码必填"""
    username = ''
    password = ''
    if username == '' or password == '':
        print("❌:账号密码未填写")
        exit()
    while True:
        if is_network_available():
            sleep_time = random.randint(50, 90)
            print(f"✅[+]{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:当前网络可用,无需再次认证!")
            time.sleep(sleep_time)
        else:
            redirect_url = get_redirect_url()
            if not redirect_url:
                continue
            ip = re.search(r'http://([a-zA-Z0-9.-]+)(:\d+)?/', redirect_url).group(1)
            query_string = re.search(r'\?(.*)', redirect_url).group(1)
            auth_url = f"http://{ip}/eportal/InterFace.do?method=login"
            data = {
            'userId': username,
            'password': password,
            'service': '',
            'queryString': query_string,
            'operatorPwd': '',
            'operatorUserId': '',
            'validcode': '',
            'passwordEncrypt': 'false',
            }
            auto_link_wifi(auth_url, data)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

# 后台自动认证

使用linux screen命令,将脚本放入screen中,并设置为后台运行。

screen -S rjauth
cd /path/to/
python3 /path/to/rjauth.py
1
2
3

按Ctrl+A+D,将脚本放入后台运行

需要查看运行情况时

screen -r rjauth
1

如果忘记了会话的命名,可以查看

screen -ls
1

回显类似

There are screens on:
    12345.my_session  (Detached)
    67890.test        (Detached)
2 Sockets in /run/screen/S-user.
1
2
3
4

那么可以这样进入会话

screen -r id/会话名
screen -r 12345    # id
screen -r my_session # 会话名
1
2
3

# 通知

后续可以添加钉钉机器人进行监控、保活,将认证结果推送到钉钉群中

最后一次更新于: 2025/03/17, 15:33:31