Python 提取本机连接过WiFi名称和密码

在 Windows 系统上用Python 获取当前电脑之前接过的 WiFi 名称及密码,并导出csv文件。

实现原理

Windows 会把所有连接过的 WiFi 配置保存在系统中,使用命令:

  • netsh wlan show profiles → 获取所有 WiFi 名称
  • netsh wlan show profile name="xxx" key=clear → 获取指定 WiFi 的密码

Python 只需要调用这些命令并解析即可。

Python 代码如下

python 复制代码
# -*- coding: utf-8 -*-
import subprocess
import re
import csv
import sys

def run_cmd(cmd):
    """执行系统命令并返回输出(永不返回 None)"""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            encoding="gbk",
            errors="ignore"
        )
        return result.stdout or ""
    except Exception as e:
        return ""

def get_wifi_list():
    """获取所有 WiFi 配置名称(兼容中英文系统)"""
    output = run_cmd("netsh wlan show profiles")

    # 兼容中文:所有用户配置文件
    # 兼容英文:All User Profile
    profiles = re.findall(
        r"(?:所有用户配置文件|All User Profile)\s*:\s*(.*)",
        output
    )

    return [p.strip() for p in profiles]

def get_wifi_password(name):
    """获取指定 WiFi 的密码(兼容中英文系统)"""
    if not name:
        return ""

    output = run_cmd(f'netsh wlan show profile name="{name}" key=clear')

    # 兼容中文:关键内容
    # 兼容英文:Key Content
    match = re.search(
        r"(?:关键内容|Key Content)\s*:\s*(.*)",
        output
    )

    return match.group(1).strip() if match else ""

def export_wifi_passwords(csv_file="wifi_passwords.csv"):
    """导出所有 WiFi 名称与密码到 CSV,并打印到 stdout(供 C# 调用)"""
    wifi_list = get_wifi_list()
    data = []

    for wifi in wifi_list:
        pwd = get_wifi_password(wifi)
        data.append([wifi, pwd])
        print(f"{wifi} : {pwd}")

    # 写入 CSV 文件
    try:
        with open(csv_file, "w", newline="", encoding="utf-8-sig") as f:
            writer = csv.writer(f)
            writer.writerow(["WiFi 名称", "密码"])
            # writer.writerows(data)
            for wifi, pwd in data:
                writer.writerow([wifi, "\t" + pwd]) # 把它当成纯文本,不会吞掉前导 0
                # writer.writerow([wifi, f"'{pwd}"])

    except Exception as e:
        print(f"写入 CSV 文件失败: {e}")

    sys.stdout.flush()  # 关键:确保 C# 能读取完整输出

if __name__ == "__main__":
    export_wifi_passwords()

运行效果

终端输出:

复制代码
WXzhongshuge : 20130423
Ritchie : ritchie12345678
KFC FREE WIFI : 
ChinaNet-Starbucks : 
RD_Meeting_Room : 57744789
1205 : W136444564
高铁WiFi : 
CMCC-JJJ2 : 12345678
H3C_E4C764 : 6575754635

已导出到文件:wifi_passwords.csv

注意事项

  • 代码仅适用于 Windows
  • 需要以 管理员权限运行 Python(否则可能读取不到密码)
  • 输出编码使用 gbk 以兼容中文系统
  • run_cmd 增加安全保护,设置参数errors="ignore"
  • 避免导出csv 文件将密码前面0省略,使用writer.writerow([wifi, "\t" + pwd]) 或writer.writerow([wifi, f'="{pwd}"'])
相关推荐
Storynone1 天前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
小鸡吃米…1 天前
Python—— 环境搭建
python
io_T_T1 天前
python 文件管理库 Path 解析(详细&基础)
python
渔阳节度使1 天前
SpringAI实时监控+观测性
后端·python·flask
铁手飞鹰1 天前
Visual Studio创建Cmake工程导出DLL,通过Python调用DLL
android·python·visual studio
飞Link1 天前
告别盲目找Bug:深度解析 TSTD 异常检测中的预测模型(Python 实战版)
开发语言·python·算法·bug
7yewh1 天前
jetson_yolo_deployment 02_linux_dev_skills
linux·python·嵌入式硬件·yolo·嵌入式
love530love1 天前
ComfyUI rgthree-comfy Image Comparer 节点无输出问题排查与解决
人工智能·windows·python·comfyui·rgthree-comfy·nodes 2.0·vue 节点
badhope1 天前
Docker从零开始安装配置全攻略
运维·人工智能·vscode·python·docker·容器·github
用户0332126663671 天前
使用 Python 复制 Excel 工作表
python