利用python脚本自动登录华农校园网(附程序)

最近刷b站,看到一位up主利用python制作了一个校园网自动连接的程序,看完很是心动。想着自己也学过python,准备尝试一下。前前后后摸索了两天,这里分享一下实现过程。

获取程序可直接跳转exe与txt获取方式

导入需要的库

import requests #请求链接
import base64 #密码加密
import os #检查文件路径
import tkinter as tk
import tkinter.messagebox as msg #设置弹窗界面

requests库安装步骤

不知道为啥我的python好像自带了需要的库(也可能是我以前用过)。如果运行时有缺少的库,可以按照下述步骤安装。这里以requests库为例。

  • 第一步: win+ R键打开运行窗口
  • 第二步:输入 cmd(如下图所示)
    利用python脚本自动登录华农校园网(附程序)
  • 第三步:输入 pip install requests

当显示 Successfully installed requests-2.27.1则说明安装完成。

在发送登录请求之前,我们要确保电脑已经连上校园网,并且能够正常访问登陆界面,python代码如下:

#检查网络连接
def check():
    url = 'http://211.69.143.97/include/auth_action.php'
    try:
        code = requests.get(url,timeout=5).status_code
        if code == 200:
            return 1
        else:
            return 0
    except:
        return 0

当函数返回值为1时说明连接正常,否则网络连接错误。(可能没有连接到校园网)

为了实现每次连接校园网时都不用重复输入账号密码,我用python写了一个建立登陆账户的函数,代码如下:

#建立登陆账户
def account():
    #生成账户文件夹
    if os.path.exists("D:/hzauwireless")==0:
        os.makedirs("D:/hzauwireless")
    #获取账号密码
    if os.path.isfile("D:/hzauwireless/account.txt")==0:    #初始化账户
        username = input("username:")
        password = input("password:")
        username = str(username)
        password = base64.b64encode(password.encode('utf-8'))    #base64转码
        password = "{B}"+str(password)[2:-1]
        line = [username,password]
        f = open("D:/hzauwireless/account.txt","w")
        f.write(username+'\n'+password)
    else:
        f = open("D:/hzauwireless/account.txt","r")    #读取账户数据
        line = f.readlines()
    return line

这里需要注意的是,在向网页发送请求时,密码经过了base64编码,因此这里要借助base64库将密码进行转码。

建立账户会在D盘生成一个名为 hzauwireless的文件夹,账号密码信息均储存在文件夹的 account.txt中。

如果你的电脑没有D盘或者不想将账户文件存在D盘,可以自行修改代码中的路径。

这是代码的核心部分,能否成功连接校园网全靠这一部分的代码。python代码如下:

#发送请求
def login(username,password):
    post_address = 'http://211.69.143.97/include/auth_action.php'

    post_headers = {
        'Connection': 'keep-alive',
        'Accept': '*/*',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }

    post_data = {
        'action': 'login',
        'username': username,
        'password': password,
        'ac_id': '5',
        'save_me': '1',
        'ajax': '1',
    }
    #发送登录请求
    z = requests.post(url=post_address, data=post_data, headers=post_headers)

    #判断请求结果
    if "login_ok" in z.text:
        show("登陆成功!")
        return 1
    elif "User not found" in z.text:
        show("用户名错误")
        return 0
    elif "Password is error" in z.text:
        show("密码错误")
        return 0
    elif "E2616" in z.text:
        show("已欠费")
        return 1    #欠费后不再重复发送请求
    else:
        #show("未知错误,报错如下:"+"\n"+z.text)
        return 0

以上就是实现校园网自动需要的三个基本部分,但为了优化界面,我还写了一个 show()函数,替换了所有的 print()函数。

这里选择使用tkinter库制作消息弹窗,python代码如下:

#定义弹窗函数
def show(str):
    tk.Tk().withdraw()    #删除多余的tk窗口
    msg.showinfo(message=str)

这部分比较简单,首先确定网络连接,然后发送请求。

[En]

This part is relatively simple, first determine the network connection, and then send the request.

为了防止一次请求发生意外,我设置了发送两次请求。

[En]

In order to prevent an accident from happening to one request, I set up to send the request twice.

对于账号密码输入错误的情况,我设置了三次错误限制,连续输入错误自动退出程序。

[En]

For the case of wrong account password input, I set the error limit three times, and the continuous input error automatically exits the program.

python代码如下:

#主程序
if check() == 1:
    i = 0    #控制循环次数
    while login(account()[0],account()[1]) == 0:
        i = i+1
        if i>3:
            show("错误次数过多")    #连续三次错误退出循环
            break
        elif i == 1:    #防止单次请求可能发生错误
            continue
        else:
            show("请重新输入")
            os.unlink("D:/hzauwireless/account.txt")
else:
    show("网络连接错误,请检查网络连接")
import requests
import base64
import os
import tkinter as tk
import tkinter.messagebox as msg

#定义弹窗函数
def show(str):
    tk.Tk().withdraw()
    msg.showinfo(message=str)

#检查网络连接
def check():
    url = 'http://211.69.143.97/include/auth_action.php'
    try:
        code = requests.get(url,timeout=5).status_code
        if code == 200:
            return 1
        else:
            return 0
    except:
        return 0

#建立登陆账户
def account():
    #生成账户文件夹
    if os.path.exists("D:/hzauwireless")==0:
        os.makedirs("D:/hzauwireless")

    #获取账号密码
    if os.path.isfile("D:/hzauwireless/account.txt")==0:    #初始化账户
        username = input("username:")
        password = input("password:")
        username = str(username)
        password = base64.b64encode(password.encode('utf-8'))    #base64编码
        password = "{B}"+str(password)[2:-1]
        line = [username,password]
        f = open("D:/hzauwireless/account.txt","w")
        f.write(username+'\n'+password)
    else:
        f = open("D:/hzauwireless/account.txt","r")    #读取账户数据
        line = f.readlines()
    return line

#发送请求
def login(username,password):
    post_address = 'http://211.69.143.97/include/auth_action.php'

    post_headers = {
        'Connection': 'keep-alive',
        'Accept': '*/*',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }

    post_data = {
        'action': 'login',
        'username': username,
        'password': password,
        'ac_id': '5',
        'save_me': '1',
        'ajax': '1',
    }

    z = requests.post(url=post_address, data=post_data, headers=post_headers)

    if "login_ok" in z.text:
        show("登陆成功!")
        return 1
    elif "User not found" in z.text:
        show("用户名错误")
        return 0
    elif "Password is error" in z.text:
        show("密码错误")
        return 0
    elif "E2616" in z.text:
        show("已欠费")
        return 1    #欠费后不再重复发送请求
    else:
        #show("未知错误,报错如下:"+"\n"+z.text)
        return 0

#主程序
if check() == 1:
    i = 0    #控制循环次数
    while login(account()[0],account()[1]) == 0:
        i = i+1
        if i>3:
            show("错误次数过多")    #连续三次错误退出循环
            break
        elif i == 1:    #防止单次请求可能发生错误
            continue
        else:
            show("请重新输入")
            os.unlink("D:/hzauwireless/account.txt")
else:
    show("网络连接错误,请检查网络连接")

为了后面便于联网启动,我们需要先将.py文件封装为.exe文件,步骤如下:

  • 第一步:打开cmd
  • 第二步:输入 pip install pyinstaller,安装pyinstaller
  • 第三步:转到.py文件所在路径
  • 第四步:输入 pyinstaller -F main.py

运行完成后可以在main.py目录下找到一个dist文件夹,双击打开后会出现一个main.exe

为了使每次连接HZAU-wireless时都能正常运行exe程序,我们需要添加一些 任务计划,步骤如下:

  • 第一步: win+ R打开运行,输入 compmgmt.msc打开计算机管理
  • 第二步: 任务计划程序-> 任务计划程序库-> 导入任务
    利用python脚本自动登录华农校园网(附程序)
  • 第三步:将 wifi自连.txt文件导入(这里注意选择文件时,将文件类型改为 所有文件
    利用python脚本自动登录华农校园网(附程序)
  • 第四步: 创建任务-> 设置
    勾选 如果过了计划开始时间,立即启动任务
    利用python脚本自动登录华农校园网(附程序)
    这解决了开机时校园网自动连接,但无法监控任务计划的问题。
    [En]

    This solves the problem that the campus network is automatically connected when the boot is started, but the task plan can not be monitored.

tip: main.exe 路径默认为 D:\hzauwireless ,如有需要,可以在 wifi自连.txt 进行修改。

Original: https://www.cnblogs.com/Easterlin/p/16314526.html
Author: Esterlin
Title: 利用python脚本自动登录华农校园网(附程序)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499483/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球