python爬虫模拟登陆校园网+连接校园wifi

时间: 2023-07-29 admin 电脑常识

python爬虫模拟登陆校园网+连接校园wifi

python爬虫模拟登陆校园网+连接校园wifi

注:本文仅作为学术交流和技术分析,所有的敏感信息全部打码,登录的账号为本人自己的账号,不涉及任何敏感行为,转载请注明

因本人在学校学习期间每次开机,都需要连接校园的wifi(学校的wifi在每次连接时,都需要向弹出网页填写数据,提交表单),觉得操作繁琐,学习的爬虫课程刚好派上用场。想着使用POST请求去模拟登陆并实现连接校园WIFI。最终实现:计算机开机自动启动脚本,进行网络(指定WIFI)连接。

首先、进入校园网的登录界面

按下F12键 打开控制台,点击登录,通过抓包发现这条请求auth_action.php

通过抓包发现为post请求,所以对需要提交的表单数据进行研究,身份类型有电信、联通、移动等,他们所对应的表单略有不同

 

 发现提交表单的数据中username栏中最后都会有一个@+字符,分别代表着三大通信运营商

爬虫思路:使用Python的requests模块中的POST方法提交页面需要的表单到网站上。页面给予反馈。提示登录成功。

代码如下:

import requests
import base64
​
# 网址
url="http://此处打码/include/auth_action.php"
headers = {
    'User-Agent': '自己电脑的请求头',
    'Referer': 'http://此处打码/srun_portal_pc.php?ac_id=2&url=此处打码',
}
username = "学号"     # 测试学号
password = "123456"     # 测试密码
# 对密码进行加密
pwd = base64.b64encode(password.encode("utf-8")).decode("ascii")
​
type_phone = {
    "电信": "@telecom",
    "移动": "@cmcc",
    "联通": "@unicom",
    # @telecom表示电信  @cmcc表示移动  @unicom表示联通
}
query_date = {
    'action': 'login',
    'username': username + type_phone["电信"],
    'password': '{B}' + pwd,  # 发现最后密码这里使用了base64加密,所以需要使用base64模块对密码进行加密
    'ac_id': '2',
    'user_ip': '',
    'nas_ip': '',
    'user_mac': '',
    'save_me': '0',
    'ajax': '1',
}
response = requests.post(url=url,headers=headers,data=query_date).content.decode("utf-8")
print(response)

模拟登陆连接校园WIFI功能已实现。但是!但是!再执行脚本的时候,发现并不是想象中的顺利,现在的脚本。启动后并不能进行连接WIFI。原因是:没有人为点击网络选择连接指定的wifi,上述代码中的网页弹不出来。

于是本人就开始了漫长的“百度”,发现:

博主:Mmagic1 的文章 用python来控制wifi连接

lizz2276 的文章 python连接wifi的模块--pywifi介绍

介绍了对应的方法。代码如下:(截取了该脚本需要的代码片段)

注:下方代码来源于Mmagic1 与 lizz2276 博主

#-*-coding:utf-8-*-
# 连接WIFI
import pywifi,time
from pywifi import const
 
def wifi_connect_status():
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0] #acquire the first Wlan card,maybe not
 
    if iface.status() in [const.IFACE_CONNECTED,const.IFACE_INACTIVE]:
        print("已连接wifi!")
        return 1
    else:
        print("没有连接到wifi!")
    
    return 0
 
def connect_wifi():
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()[0]
    print(ifaces.name())               #输出无线网卡名称
    ifaces.disconnect()
    time.sleep(3)
 
    profile = pywifi.Profile()                          #配置文件
    profile.ssid = "校园网WIFI"                        #wifi名称
    # 因为校园网在点击连接的时候并不像其他WIFI一样直接输入密码。所以我注释掉了下面一部分代码
    #profile.auth = const.AUTH_ALG_OPEN                  #需要密码
    #profile.akm.append(const.AKM_TYPE_WPA2PSK)          #加密类型
    #profile.cipher = const.CIPHER_TYPE_CCMP             #加密单元
    #profile.key = "88888888"                            #wifi密码
 
    ifaces.remove_all_network_profiles()                #删除其它配置文件
    tmp_profile = ifaces.add_network_profile(profile)   #加载配置文件
    ifaces.connect(tmp_profile)
    time.sleep(5)
    isok = True
 
    if ifaces.status() == const.IFACE_CONNECTED:
        print("连接成功!")
    else:
        print("连接失败!")
 
    time.sleep(1)
    return isok
 
def main():
    print("start")
    wifi_connect_status()
    connect_wifi()
    print("finish!")
 
if __name__ == "__main__":
    main()
​
# 原文链接:/Mmagic1/article/details/120066894

可以实现打开wifi并点击的功能

模块pywifi在使用的时候可能会出现下面报错

报错ModuleNotFoundError: No module named ‘comtypes‘

解决办法:只需要将报错信息中的模块comtypes,进行下载即可

参考:码诗~ 文章 导入pywifi时,报错ModuleNotFoundError: No module named ‘comtypes‘

最终代码展示:

import requests
import base64
import pywifi, time
from pywifi import const
​
"""
首先、安装 comtypes,pywifi,requests,pyinstaller 模块
 pip install pywifi
 pip install requests
 pip install comtypes
 pip install pyinstaller 

其次、编辑self_date 修改字典中的数据。
执行脚本。
"""
​
​
class Login_Wifi(object):
​
    def __init__(self,username,password):
        # 账号密码
        self.username = username
        self.password = password
        # 对密码进行加密
        self.pwd = base64.b64encode(password.encode("utf-8")).decode("ascii")
        self.type_phone = {
            "电信": "@telecom",
            "移动": "@cmcc",
            "联通": "@unicom",
            # @telecom表示电信  @cmcc表示移动  @unicom表示联通
        }
​
        self.url="http://此处打码/include/auth_action.php"
        self.headers = {
            'User-Agent': '自己电脑的请求头',
            'Referer': 'http://此处打码/srun_portal_pc.php?ac_id=2&url=此处打码',
        }
​
    def spider_login(self):
​
        url = self.url
        headers = self.headers
​
        query_date = {
            'action': 'login',
            'username': self.username + self.type_phone["电信"],
            'password': '{B}' + self.pwd,
            'ac_id': '2',
            'user_ip': '',
            'nas_ip': '',
            'user_mac': '',
            'save_me': '0',
            'ajax': '1',
        }
​
        response = requests.post(url=url,headers=headers,data=query_date).content.decode("utf-8")
        print(response)
        print("end")
        return response
​
​
class Content_Wifi(Login_Wifi):
    def __init__(self,username,password,wifi_name):
        Login_Wifi.__init__(self,username,password)
        self.wifi_name = wifi_name
​
​
    def wifi_connect_status(self):
        print("start")
        wifi = pywifi.PyWiFi()  # 定义接口操作
        iface = wifi.interfaces()[0]  # 这里iface就是获取的wifi接口
​
        if iface.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
            print("已连接wifi!")
            return 1
        else:
            print("没有连接wifi!")
​
        return 0
​
    def connect_wifi(self):
        wifi = pywifi.PyWiFi()  #生成对象而已,接下来就能对他进行配置操作了
        ifaces = wifi.interfaces()[0]
        print(ifaces.name())  # 输出无线网卡名称
        ifaces.disconnect()
        time.sleep(3)
​
        profile = pywifi.Profile()  # 配置文件
        profile.ssid = self.wifi_name  # wifi名称   "XZCIT-WIFI"
        ifaces.remove_all_network_profiles()  # 删除其它配置文件
        tmp_profile = ifaces.add_network_profile(profile)  # 加载配置文件
        ifaces.connect(tmp_profile)
        time.sleep(5)
        isok = True
​
        if ifaces.status() == const.IFACE_CONNECTED:
            print("连接成功!")
        else:
            print("连接失败")
​
        time.sleep(1)
        return isok
​
​
​
if __name__ == '__main__':
    self_date = {
        "username":"学号",   # 测试账号
        "password":"123456",         # 测试密码
    }
    wifi_content = Content_Wifi(
        username=self_date['username'],
        password=self_date['password'],
        wifi_name="校园WIFI"      # 校园WIFI
    )
    wifi_content.wifi_connect_status()
    wifi_content.connect_wifi()
    wifi_content.spider_login()
​

利用模块 Pyinstaller 生成 脚本.exe文件。附图

最后就是整个项目的部署与实现开机自启动。

将生成的.exe可执行文件发送到桌面快敏捷方式——>win+r调出运行框,并输入shell:startup打开启动——>将快敏捷方式放到其中。

大功告成啦!!!!!!!!!!

注:本文仅作为学术交流和技术分析,所有的敏感信息全部打码,登录的账号为本人自己的账号,不涉及任何敏感行为,转载请注明