在 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}"'])