Automating Campus Network Login and Wi‑Fi Connection on macOS with Python
This tutorial explains how to programmatically log into a campus network by analyzing HTTP requests, crafting POST data, retrieving the local IP address, automating Wi‑Fi connection on macOS using pywifi, and finally packaging the script into a standalone executable with pyinstaller.
The article begins with a personal note about acquiring a MacBook and the desire to automate the cumbersome campus network login process that normally requires a browser login popup.
1. Implementation principle – By using the HTTP protocol, the script locates the login page URL, sends a POST request with the required credentials, and receives a successful login response.
1.1 Understanding URL – A URL (Uniform Resource Locator) follows the format protocol://username:[email protected]:port/path/file?param=value#fragment . Parts such as username, password, and query parameters can be omitted depending on the request.
1.2 HTTP request message format – The request consists of a start line ( method URL version ), headers (key: value pairs separated by newlines), a blank line, and an optional body. Common headers include Content-Type , Content-Length , Host , User-Agent , etc.
1.3 HTTP response header format – The response starts with version status_code reason_phrase , followed by headers and an optional body containing the returned HTML page.
2. Concrete implementation
First, install the requests library (if not already present) with pip3 install requests . Then use the following Python code to obtain the local IP address and send the login request:
import requests
import socket
def get_host_ip():
"""Query the machine's IP address"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
finally:
s.close()
return ip
user_ip = get_host_ip()
post_addr = "http://10.10.244.11:801/eportal/"
post_header = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': '10.10.244.11',
'Referer': 'http://10.10.244.11/',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36'
}
post_data = {
'c': 'ACSetting',
'a': 'Login',
'DDDDD': 'xxxx',
'upass': 'xxxxx',
'protocol': 'http:',
'hostname': '10.10.244.11',
'iTermType': '1',
'wlanuserip': user_ip,
'wlanacip': 'xxxxxx',
'wlanacname': 'SPL-BRAS-SR8806-X',
'mac': '00-00-00-00-00-00',
'ip': user_ip,
'enAdvert': '0',
'queryACIP': '0',
'loginMethod': '1'
}
z = requests.post(post_addr, data=post_data, headers=post_header)
print("登录校园网成功,局域网ip如下:")
print(user_ip)To automate Wi‑Fi connection, install pywifi (note that the original package does not support macOS, so a macOS‑compatible fork from GitHub must be used). After cloning the fork, replace the original package files with the macOS version.
pip3 install pywifi
# Clone macOS‑compatible fork
git clone -b macos_dev https://github.com/awkman/pywifi.git
# Replace the package directory (example path)
cp -r pywifi /Users/yourname/Library/Python/3.8/lib/python/site-packages
pip3 install pyobjc # required dependency for macOSUse the following script to check Wi‑Fi status, scan available networks, and connect to the campus Wi‑Fi (SSID "NJUPT-CMCC") without a password:
import pywifi, time
from pywifi import const
def wifi_connect_status():
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
if iface.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
return 1
else:
print("Please enable Wi‑Fi manually.")
return 0
def scan_wifi():
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
iface.scan()
time.sleep(1)
return iface.scan_results()
def connect_wifi():
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
iface.disconnect()
time.sleep(3)
profile = pywifi.Profile()
profile.ssid = "NJUPT-CMCC"
iface.remove_all_network_profiles()
tmp_profile = iface.add_network_profile(profile)
iface.connect(tmp_profile)
time.sleep(1)
if iface.status() == const.IFACE_CONNECTED:
print("连接校园网成功")
return True
else:
print("连接校园网失败")
return FalseFinally, package the whole script into a Windows executable using pyinstaller :
pip3 install pyinstaller
/Users/yourname/Library/Python/3.8/bin/pyinstaller -F your_script.pyThe command creates a dist folder containing the .exe file, completing the automation workflow.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.