乐于分享
好东西不私藏

WHUT校园网自动登录(PC端)

WHUT校园网自动登录(PC端)

由于武汉理工大学校园网每隔几天就要重新登陆一次,本人想实现放假期间实验室windows电脑自动开机,自动连网实现远程控制,所以根据网友的代码进行的优化,完成了基于Python脚本的校园网自动登陆功能。

Python脚本

import timeimport osimport randomimport requestswith open(r'E:\Pycode\Pytorch\Other\data.ini''r', encoding='utf=8'as f:    a = f.readlines()username = a[0].strip()password = a[1].strip()usermac = a[2].strip()print(f"用户名为:{username}\t\n密码为:{password}\t\nMAC地址为:{usermac}\t\n")file = open(r"E:\Pycode\Pytorch\Other\log.txt""a+", encoding="utf8")os.system('chcp 65001')  # 解决控制台中文乱码def connect():    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))    # 网络连通exit_code==0,否则返回非0值。    exit_code = os.system('ping www.baidu.com')    if exit_code == 0:        file.write(now_time + '\t' + "网络已连通")        file.close()        return True    else:        s = requests.session()        res1 = s.post(            url=r"http://172.30.16.34/srun_portal_pc.php",            headers={                "Accept""*/*",                "Accept-Encoding""gzip, deflate",                "Accept-Language""zh-CN,zh;q=0.9",                "Cache-Control""no-cache",                "Connection""keep-alive",                "Content-Length""117",                "Content-Type""application/x-www-form-urlencoded;charset=UTF-8",                "Cookie"r"",                "Host""172.30.16.34",                'Origin''http://172.30.16.34',                'X-Requested-With''XMLHttpRequest',                "Referer""",                "User-Agent""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64;"                              " Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; "                              ".NET CLR 3.5.30729; Tablet PC 2.0)",            },            data={                "ac_id": random.choice([x for x in range(100)]),  # 一般登陆不上改这里,ac_id会变                "action""login",                "ajax""1",                "nas_ip"'',                "save_me""1",                "user_ip"'',                "username": username,                "password": password,                "user_mac": usermac,            },        )        content = res1.content        content = content.decode()        file.write(now_time + '\t' + content + "\n")        print(now_time + '\t' + content)        return Falseif __name__ == "__main__":    status = False    while not status:        status = connect()

其中,data.ini文件内容如下:

校园卡号校园网密码本机的Mac地址

本人亲测输出如下(测试地点:鉴湖),因为发现有时根据登陆的返回状态为login_oksuccessful并未真正连上网络,故增加了一个循环,同时测试网络是否连通。

Pinging www.baidu.com [112.80.248.76with 32 bytes of data:Request timed out.Request timed out.Request timed out.Request timed out.Ping statistics for 112.80.248.76:    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),2022-01-03 10:55:25	Portal not response-4.()Pinging www.baidu.com [112.80.248.76with 32 bytes of data:Request timed out.Request timed out.Request timed out.Request timed out.Ping statistics for 112.80.248.76:    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),2022-01-03 10:55:47	login_ok,,bQ0pOyR6IXU7PJaQQqRAcBPxGAvxAcrvEe0UJFGSwjYoIkI%2BuqigThe1hwF7wzKKjJa0up53uv%2FSiO28eoHG%2F09yjnF60B01nG0mbf%2Bb8eTxICQp%2F29oDCDKLtz3CujariYJbSJ9rEKbCpk3Qqo9P7ci8MWK2r10GQy2UTb64I44t1MpS5X19%2B0ui8ZUV9%2B0HIDk5lT0Cg2H0Sjkm0ZWaKpKmK0fKAci22%2BHQqCEAwqoPinging www.baidu.com [112.80.248.75with 32 bytes of data:Request timed out.Reply from 112.80.248.75: bytes=32 time=13ms TTL=53Reply from 112.80.248.75: bytes=32 time=13ms TTL=53Reply from 112.80.248.75: bytes=32 time=13ms TTL=53Ping statistics for 112.80.248.75:    Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),Approximate round trip times in milli-seconds:    Minimum = 13ms, Maximum = 13ms, Average = 13msProcess finished with exit code 0

设置开机自动执行

本人采用的是windows计划任务完成,首先写一个bat批处理命令来自动执行python脚本,然后再将bat加入到windows计划任务中即可。

bat命令脚本如下:

@echo off			#关闭运行命令本身的显示start  "connect_Net" "C:\Windows\System32\cmd.exe" 		# 打开cmd程序python E:\Pycode\Pytorch\Other\Login.py			# 执行python脚本,需要修改路径taskkill /f /im cmd.exe			# 执行结束后kill掉cmd程序exit

windows计划任务如何添加方法:https://blog.csdn.net/cdnight/article/details/53841921

参考:https://blog.csdn.net/haostart_/article/details/110249574

新版本校园网自动登陆

由于2023年2月开始,校园网进行了优化升级,访问接口有了变化,故新程序更新如下,参考Github:

# coding:utf-8import loggingimport requestsimport base64import reimport sysimport timeimport socketrequesr_url = ''logging.basicConfig(level=logging.INFO,                    format='%(levelname)s: %(asctime)s ====> %(message)s')session = requests.Session()session.trust_env = Falsedef login_request(username, password) -> bool:    file = open(r"E:\Pycode\Pytorch\Other\log.txt""a+", encoding="utf8")    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))    if not is_net_ok():        # log_out()        # time.sleep(5)        logging.info("your computer is offline,request now...")        # password = "{B}" + base64.b64encode(password.encode()).decode()  # 加密        nasId = getNasId()        logging.info('nasId: ' + str(nasId))        data = {            "username": username,            "password": password,            "nasId": nasId        }        headers = {            'User-Agent':            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',            'accept-encoding''gzip, deflate',            'Cache-Control''max-age=0',            'Connection''keep-alive',            'accept-language''zh-CN,zh-TW;q=0.8,zh;q=0.6,en;q=0.4,ja;q=0.2',            'Content-Type''application/x-www-form-urlencoded; charset=UTF-8',            'X-Requested-With''XMLHttpRequest',        }        # if not is_login_as_pc:        #     headers['User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Mobile Safari/537.36'        try:            response = session.post(requesr_url, data=data, headers=headers)            response.encoding = response.apparent_encoding            # print(response.text)            if '"authCode":"ok' in response.text:                logging.info("login successfully")                user_ip = get_user_ip(response.text)                host_ip = get_host_ip()                logging.info("your user ip: " + user_ip)                logging.info("your host ip: " + host_ip)                file.write(now_time + '\t' + "login successfully, your user ip: " + user_ip + "\n")            else:                logging.error(response.text)        except Exception:            logging.exception("requsest error")    else:        logging.info("your computer is online  ")        host_ip = get_host_ip()        logging.info("your host ip: " + host_ip)        file.write(now_time + '\t' + "login successfully, your host ip: " + host_ip + "\n")    file.close()def is_net_ok() -> bool:    try:        status = session.get("https://www.baidu.com").status_code        if status == 200:            return True        else:            return False    except Exception:        return Falsedef get_host_ip():    try:        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        s.connect(('8.8.8.8'80))        ip = s.getsockname()[0]    finally:        s.close()    return ipdef get_user_ip(response_text):    match_list = re.findall(r'"UserIpv4":"(.*?)"', response_text, re.S)    if len(match_list) == 0:        return -1    ip = match_list[0]    return ipdef getNasId() -> int:    response = session.get(        'http://www.msftconnecttest.com/redirect?cmd=redirect')    url = response.url    with open('request_host_url.txt''w'as f:        f.write(url)    response = session.get(url + 'api/config')    match_list = re.findall(r'"default_nas":"(.*?)"', response.text, re.S)    if len(match_list) == 0:        return -1    nasId_str = match_list[0]    nasId = int(nasId_str)    global requesr_url    requesr_url = url + '/api/account/login'    return nasIddef heading():    passif __name__ == "__main__":    heading()    #args = sys.argv    username = "username"   # 此处修改卡号和密码    password = "password"    while True:        try:            login_request(username, password)            break        except:            logging.exception("Connection refused by the server..")            logging.exception("Let me sleep for 5 seconds")            time.sleep(5)            logging.info("Was a nice sleep, now let me continue...")            continue

使用Edge浏览器自动化程序

参考资料:https://learn.microsoft.com/zh-cn/microsoft-edge/webdriver/?tabs=python

注意: 必须安装浏览器驱动程序 (Microsoft Edge WebDriver) ,将其放置到与Py文件相同的位置,或者将其放到Python程序所在的同级目录。

from selenium import webdriverfrom selenium.webdriver.common.by import Byimport timeimport requestsdef open_broswer_login(sleep_time=5):    driver = webdriver.Edge()    driver.get('http://www.whut.edu.cn/')    element = driver.find_element(By.ID, 'username')    element.send_keys(username)    time.sleep(sleep_time)    element = driver.find_element(By.ID, 'password')    element.send_keys(password)    time.sleep(sleep_time)    driver.find_element(By.ID, 'login-account').click()    time.sleep(sleep_time)    driver.quit()def is_net_ok() -> bool:    for i in range(5):        print(f'try {i}-th time')        try:            status_code = requests.get("https://www.baidu.com").status_code            print(status_code)            if status_code == 200:                return True                break        except Exception as e:            print(f'there is a exception: {e}')            open_broswer_login()if __name__ == "__main__":    print(__name__)    username = "321147"    password = "wuxiaohua9077"    file = open(r"E:\Pycode\Pytorch\Other\Login_WHUT_Network\log.txt""a+", encoding="utf8")    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))    status = is_net_ok()    print(status)    if status:        file.write(now_time + '\t' + "login successfully!\n")    else:        file.write(now_time + '\t' + "Error!\n")

有需要也可后台留言,可以协助解决,实现每天电脑开机之后自动验证网络通断状态,如果网络不通,会自动打开浏览器,登陆账号,然后关闭浏览器,实现用户无感。