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}"')
相关推荐
Dmz丶11 小时前
前端转 AI 100 天 Day 48:向量数据库——100 万向量的毫秒级检索
python
青少儿编程课堂11 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中国剩余定理解析
c++·python·算法·bfs·信息学竞赛
菜鸟~noob23311 小时前
[AI]间章:系列走到这里,聊聊后面的规划、造卡需要的软件平台,以及为什么我要先暂停更新
人工智能·python·fpga开发·django·pygame
TomEval21 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
prince_zxill1 天前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751
Thanks_ks1 天前
Python 的垃圾回收——引用计数撑起日常,分代回收收拾残局
python·内存管理·垃圾回收·循环引用·引用计数·gc 模块·weakref
CyrusYiVPP1 天前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
yiangL_1 天前
Python 学习笔记:递归、turtle绘图、字符串与函数
笔记·python·学习
lula8881 天前
PVC-U、PVC-C、PVC-O 差一个字母,差的是三种增强路线
python
数字工作台1 天前
给 LangGraph 加一道可审计记忆:替换默认 Checkpointer,实现防篡改 + 崩溃不丢数据
python·agent