Python跨系统实现WiFi连接的最简方法,仅需SSID与密码
Python跨系统WiFi连接实现方案
核心思路
跨操作系统WiFi连接没有通用的原生Python API,本方案通过封装各系统自带的命令行WiFi管理工具实现,仅依赖Python标准库,无需GUI界面介入,满足树莓派(Linux)、Windows多平台适配需求,仅需传入SSID和密码即可完成连接。
前置要求
- 仅依赖Python内置标准库:
subprocess、platform、re,无需安装第三方包 - Linux/树莓派侧需预装
NetworkManager(主流树莓派官方镜像默认自带,缺失可执行apt install network-manager安装) - 脚本运行需对应权限:Linux端需sudo权限,Windows端需以管理员身份运行
完整实现代码
import subprocess import platform import re def connect_wifi(ssid: str, password: str) -> bool: system = platform.system() # 适配Windows系统 if system == "Windows": # 检查是否已有保存的配置 profile_res = subprocess.run( ["netsh", "wlan", "show", "profiles"], capture_output=True, text=True, encoding="gbk" ) has_saved = ssid in re.findall(r"所有用户配置文件\s*:\s*(.*)", profile_res.stdout) if has_saved: # 直接用已有配置连接 connect_res = subprocess.run( ["netsh", "wlan", "connect", f"name={ssid}"], capture_output=True, text=True, encoding="gbk" ) return "已成功完成连接" in connect_res.stdout else: # 生成临时配置XML profile_xml = f"""<?xml version="1.0"?> <WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1"> <name>{ssid}</name> <SSIDConfig> <SSID> <name>{ssid}</name> </SSID> </SSIDConfig> <connectionType>ESS</connectionType> <connectionMode>auto</connectionMode> <MSM> <security> <authEncryption> <authentication>WPA2PSK</authentication> <encryption>AES</encryption> <useOneX>false</useOneX> </authEncryption> <sharedKey> <keyType>passPhrase</keyType> <protected>false</protected> <keyMaterial>{password}</keyMaterial> </sharedKey> </security> </MSM> </WLANProfile>""" # 写入临时文件 with open(f"{ssid}_profile.xml", "w", encoding="utf-8") as f: f.write(profile_xml) # 添加配置 add_res = subprocess.run( ["netsh", "wlan", "add", "profile", f"filename={ssid}_profile.xml"], capture_output=True, text=True, encoding="gbk" ) # 删除临时文件 import os os.remove(f"{ssid}_profile.xml") if "已成功添加" not in add_res.stdout: return False # 执行连接 connect_res = subprocess.run( ["netsh", "wlan", "connect", f"name={ssid}"], capture_output=True, text=True, encoding="gbk" ) return "已成功完成连接" in connect_res.stdout # 适配Linux/树莓派系统 elif system == "Linux": # 检查是否已有保存的配置 profile_res = subprocess.run( ["nmcli", "con", "show"], capture_output=True, text=True ) has_saved = ssid in [line.split()[0] for line in profile_res.stdout.splitlines()] if has_saved: # 直接连接已有配置 connect_res = subprocess.run( ["nmcli", "con", "up", "id", ssid], capture_output=True, text=True ) return connect_res.returncode == 0 else: # 新建配置并连接 connect_res = subprocess.run( ["nmcli", "dev", "wifi", "connect", ssid, "password", password], capture_output=True, text=True ) return connect_res.returncode == 0 else: # 暂不支持其他系统 return False # 调用示例 if __name__ == "__main__": result = connect_wifi("你的WiFi名称", "你的WiFi密码") print("连接成功" if result else "连接失败")
功能说明
- 自动适配平台:运行时自动识别当前操作系统,调用对应原生命令
- 历史网络复用:自动检测目标SSID是否为已保存的网络,已保存则直接调用现有配置连接,无需重复验证密码
- 无GUI依赖:全程走命令行调用,不会弹出任何系统WiFi选择界面
- 结果可校验:返回布尔值标识连接结果,可自行扩展捕获密码错误、SSID不存在等异常场景
注意事项
- 代码默认适配WPA2/WPA3加密的WiFi,如需适配WEP等老旧加密方式可自行修改对应系统的命令参数
- 树莓派如果使用未带NetworkManager的精简镜像,可将Linux部分的
nmcli命令替换为wpa_cli或修改wpa_supplicant.conf的逻辑实现 - 如SSID或密码包含特殊字符,使用代码中的列表形式传参可避免命令注入问题,无需额外转义
内容的提问来源于stack exchange,提问作者lex
相关产品推荐
相关产品推荐

