You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python在Linux/Windows中连接未关联过的WiFi(输入SSID、PASSWORD)

Python实现跨系统连接未配对WiFi方案

本方案通过调用系统原生命令工具实现,无需额外安装第三方硬件驱动类依赖,仅需传入目标WiFi的SSID、密码两个入参即可完成从未配对过的WiFi网络连接。

实现原理

Python本身未提供原生的WiFi操作API,本方案通过subprocess模块调用各系统自带的网络配置命令完成操作:

  • Windows系统调用内置的netsh命令行工具
  • Linux系统调用内置的nmcli(NetworkManager命令行工具,主流桌面发行版默认预装)

完整可运行代码

import subprocess
import sys
import os

def connect_new_wifi(ssid: str, password: str) -> bool:
    """
    连接从未配对过的WiFi网络
    :param ssid: 目标WiFi的SSID名称
    :param password: 目标WiFi的密码
    :return: 连接成功返回True,失败返回False
    """
    # Windows系统处理逻辑
    if sys.platform == "win32":
        # 生成netsh需要的WiFi配置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>"""
        # 写入临时XML文件
        with open("wifi_profile.xml", "w", encoding="utf-8") as f:
            f.write(profile_xml)
        try:
            # 添加WiFi配置文件
            add_profile_cmd = ["netsh", "wlan", "add", "profile", "xmlfile=wifi_profile.xml"]
            subprocess.run(add_profile_cmd, check=True, capture_output=True, text=True, shell=False)
            # 连接WiFi
            connect_cmd = ["netsh", "wlan", "connect", f"name={ssid}"]
            subprocess.run(connect_cmd, check=True, capture_output=True, text=True, shell=False)
            return True
        except subprocess.CalledProcessError:
            return False
        finally:
            # 删除临时XML文件
            if os.path.exists("wifi_profile.xml"):
                os.remove("wifi_profile.xml")
    # Linux系统处理逻辑
    elif sys.platform == "linux":
        try:
            connect_cmd = ["nmcli", "dev", "wifi", "connect", ssid, "password", password]
            subprocess.run(connect_cmd, check=True, capture_output=True, text=True, shell=False)
            return True
        except subprocess.CalledProcessError:
            return False
    # 其他系统暂不支持
    else:
        return False

# 调用示例
if __name__ == "__main__":
    target_ssid = "替换为你的WiFi名称"
    target_pwd = "替换为你的WiFi密码"
    result = connect_new_wifi(target_ssid, target_pwd)
    print("连接成功" if result else "连接失败")

注意事项

  • Windows环境下运行代码需要管理员权限,否则无法添加WiFi配置文件
  • Linux环境下需要确保NetworkManager服务处于运行状态,且当前用户属于netdev用户组(或使用root权限运行)
  • 仅支持WPA/WPA2个人级加密的WiFi网络,企业级802.1X认证的WiFi需要额外调整配置参数
  • 代码通过列表形式传递命令参数,避免了SSID、密码包含特殊字符时的命令注入风险

内容的提问来源于stack exchange,提问作者RRIIZZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:15:07