Python自动连接已保存WiFi

一、核心方法选择

根据系统环境选择最佳方案:

  • Windows系统 :优先使用pywifi库或netsh命令
  • Linux系统 :推荐nmcli命令或wifi
  • macOS系统 :需结合CoreWLAN框架

二、Windows系统实现方案

方法1:使用pywifi库(推荐)

python 复制代码
import pywifi
from pywifi import const
import time

def connect_saved_wifi(ssid):
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]  # 获取第一个无线网卡
    
    # 断开当前连接
    iface.disconnect()
    time.sleep(1)
    
    # 创建配置文件(密码已保存在系统)
    profile = pywifi.Profile()
    profile.ssid = ssid
    profile.auth = const.AUTH_ALG_OPEN
    profile.akm.append(const.AKM_TYPE_WPA2PSK)
    profile.cipher = const.CIPHER_TYPE_CCMP
    
    # 清理旧配置并连接
    iface.remove_all_network_profiles()
    tmp_profile = iface.add_network_profile(profile)
    iface.connect(tmp_profile)
    
    # 等待连接完成
    time.sleep(5)
    return iface.status() == const.IFACE_CONNECTED

# 使用示例
if __name__ == "__main__":
    target_ssid = "Your_WiFi_SSID"
    if connect_saved_wifi(target_ssid):
        print(f"✅ 成功连接到 {target_ssid}")
    else:
        print(f"❌ 连接 {target_ssid} 失败,请检查网络设置")

方法2:调用netsh命令

python 复制代码
import subprocess

def connect_saved_network(ssid):
    command = f'netsh wlan connect name="{ssid}"'
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    
    if "已连接" in result.stdout:
        return True
    elif "无法连接" in result.stdout:
        print("⚠️ 网络不可用或配置文件不存在")
    else:
        print(f"错误信息:{result.stderr}")
    return False

# 使用示例
target_ssid = "Office_WiFi"
connect_saved_network(target_ssid)

三、关键注意事项

  1. 权限要求

    • Windows需以管理员身份运行脚本
    • Linux需sudo权限或用户组权限
    • macOS需在系统偏好设置中授权
  2. 网络配置验证

    python 复制代码
    # 验证连接状态
    def check_connection():
        output = subprocess.check_output('netsh wlan show interfaces', shell=True).decode()
        if "已连接" in output:
            return True
        return False
  3. 跨平台适配建议

    python 复制代码
    import platform
    system = platform.system()
    
    if system == "Windows":
        # 使用netsh或pywifi
    elif system == "Linux":
        # 使用nmcli命令
    elif system == "Darwin":
        # 使用CoreWLAN框架

四、常见问题解决

  1. 连接失败处理

    • 检查SSID是否正确
    • 验证网络配置文件是否存在:netsh wlan show profiles
    • 重启WLAN服务:netsh winsock reset
  2. 性能优化

    python 复制代码
    # 添加超时重试机制
    for attempt in range(3):
        if connect_saved_wifi(ssid):
            break
        time.sleep(5)
  3. 安全提示

    • 避免在代码中硬编码密码
    • 使用环境变量存储敏感信息
    • 定期更新库版本保持兼容性

五、扩展功能

  1. 自动选择最佳信号

    python 复制代码
    def select_best_network():
        scan_results = iface.scan_results()
        best_network = max(scan_results, key=lambda x: x.signal)
        return best_network.ssid
  2. 定时自动连接

    python 复制代码
    # Windows任务计划程序配置
    # 创建.bat文件调用python脚本
    # 设置触发器为开机启动或定时执行
  3. 多网卡支持

    python 复制代码
    # 遍历所有无线网卡
    for iface in wifi.interfaces():
        if iface.name() == "Wi-Fi 2":
            target_iface = iface

通过以上方案,可实现跨平台的WiFi自动连接功能。实际部署时建议添加日志记录和异常捕获机制,确保系统稳定性。如遇特殊网络环境,可结合系统API进行深度定制。

相关推荐
毕设源码-邱学长4 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
rookieﻬ°5 小时前
PHP框架漏洞
开发语言·php
猿界零零七5 小时前
pip install mxnet 报错解决方案
python·pip·mxnet
炸膛坦客6 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
兑生6 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
炸膛坦客7 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲7 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
不只会拍照的程序猿7 小时前
《嵌入式AI筑基笔记02:Python数据类型01,从C的“硬核”到Python的“包容”》
人工智能·笔记·python
Jay_Franklin7 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824968 小时前
代码性能剖析工具
开发语言·c++·算法