1. 为什么需要提取WiFi密码?
在日常工作中,我们经常遇到这样的场景:新设备需要连接WiFi但忘记了密码,或者需要批量管理多个设备的网络配置。作为IT运维人员,我经常需要为同事的设备配置网络,手动询问密码不仅效率低下,还存在安全隐患。Windows系统虽然会记住连接过的WiFi密码,但默认不直接显示明文,这就催生了用Python自动化提取的需求。
注意:本文方法仅适用于合法获取自己设备的WiFi信息,禁止用于非法获取他人网络凭证。
2. 环境准备与原理分析
2.1 必备工具清单
- Python 3.6+(推荐3.9+)
- Windows系统(Win7/Win10/Win11测试通过)
- 管理员权限的CMD/PowerShell
- 第三方库:subprocess、csv、re
2.2 技术实现原理
Windows将所有连接过的WiFi配置(包括密码)加密存储在注册表中,具体路径为:
code复制HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles
通过netsh wlan show profiles命令可以列出所有保存的WiFi名称,再对每个名称执行netsh wlan show profile name="WiFi名称" key=clear即可显示包含密码的详细信息。
3. 完整实现代码解析
3.1 基础版本实现
python复制import subprocess
import re
def get_wifi_profiles():
"""获取所有保存的WiFi配置名称"""
result = subprocess.run(['netsh', 'wlan', 'show', 'profiles'],
capture_output=True, text=True)
return re.findall(r':\s(.*?)\r', result.stdout)
def get_wifi_password(profile):
"""获取指定WiFi配置的密码"""
cmd = f'netsh wlan show profile name="{profile}" key=clear'
result = subprocess.run(cmd, capture_output=True, text=True, shell=True)
match = re.search(r'Key Content\s*:\s(.*?)\r', result.stdout)
return match.group(1) if match else ""
if __name__ == '__main__':
profiles = get_wifi_profiles()
for profile in profiles:
print(f"{profile}: {get_wifi_password(profile)}")
3.2 增强版(带CSV导出)
python复制import csv
from datetime import datetime
# ...(保留上述两个函数)
def export_to_csv(profiles):
"""将结果导出到CSV文件"""
filename = f"wifi_passwords_{datetime.now().strftime('%Y%m%d_%H%M')}.csv"
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['WiFi名称', '密码'])
for profile in profiles:
writer.writerow([profile, get_wifi_password(profile)])
return filename
if __name__ == '__main__':
profiles = get_wifi_profiles()
csv_file = export_to_csv(profiles)
print(f"结果已导出到: {csv_file}")
4. 常见问题与解决方案
4.1 权限不足报错处理
当看到请求的操作需要提升(管理员权限)错误时:
- 右键点击Python脚本选择"以管理员身份运行"
- 或者在CMD中先运行:
code复制runas /user:Administrator "python script.py"
4.2 中文WiFi名称乱码
在导出CSV时指定编码为utf-8:
python复制with open('output.csv', 'w', newline='', encoding='utf-8-sig') as f:
# 使用utf-8-sig解决Excel打开乱码问题
4.3 部分WiFi无法获取密码
可能原因及解决方案:
- 企业级WPA2-Enterprise网络:密码由证书验证,无法直接获取
- 手动输入密码但未勾选"记住密码":系统未保存密码
- 系统策略限制:需检查组策略编辑器中的相关设置
5. 安全增强建议
5.1 密码存储安全
生成的CSV文件建议:
- 立即加密压缩(使用7z/AES256)
- 传输使用SFTP/HTTPS
- 使用后及时删除
5.2 代码安全改进
python复制# 在敏感操作前添加确认提示
import getpass
if input("确认导出WiFi密码?(y/n)").lower() != 'y':
exit()
# 密码显示用*号替代
def mask_password(pwd):
return pwd[:2] + '*'*(len(pwd)-2) if pwd else ""
6. 实际应用场景扩展
6.1 批量部署工具集成
将脚本集成到IT运维工具包中,结合PyInstaller打包成exe:
code复制pyinstaller --onefile --icon=wifi.ico wifi_password_extractor.py
6.2 自动化网络测试框架
结合pytest实现自动化网络测试:
python复制import pytest
@pytest.fixture(scope='module')
def wifi_credentials():
return {p:get_wifi_password(p) for p in get_wifi_profiles()}
def test_network_connection(wifi_credentials):
for name, pwd in wifi_credentials.items():
# 实现自动连接测试逻辑
assert connect_to_wifi(name, pwd)
我在实际使用中发现,Windows 11 22H2版本后,部分网络配置的存储位置有所变化。如果遇到无法获取的情况,可以尝试检查注册表路径:
code复制HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WcmSvc\WiFiNetworkManager\Configurations
