Python调用netsh获取WiFi密码运行报找不到netsh错误
问题说明
运行用于提取已连接WiFi密码的Python脚本时,抛出如下错误:
No such file or directory: 'netsh'
原问题代码如下:
import subprocess meta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']) data = meta_data.decode('utf-8', errors ="backslashreplace") data = data.split('\n') profiles = [] for i in data: if "All User Profile" in i : i = i.split(":") i = i[1] i = i[1:-1] profiles.append(i) print("{:<30}| {:<}".format("Wi-Fi Name", "Password")) print("----------------------------------------------") for i in profiles: try: results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key = clear']) results = results.decode('utf-8', errors ="backslashreplace") results = results.split('\n') results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b] try: print("{:<30}| {:<}".format(i, results[0])) except IndexError: print("{:<30}| {:<}".format(i, "")) except subprocess.CalledProcessError: print("Encoding Error Occurred")
故障原因
netsh是Windows系统专属的内置网络管理命令,非Windows系统(macOS、Linux等)无此命令,运行会直接报找不到文件- Windows环境下如果VS Code加载的系统环境变量异常,Python subprocess模块无法从默认搜索路径定位到netsh.exe
- 原代码存在参数书写错误:查询密码的参数写为
key = clear,等号两侧多余空格会导致命令执行失败,就算解决路径问题也无法正常提取密码
修复方案
- 确认运行环境:该脚本逻辑仅适配Windows系统,非Windows系统需要替换为对应系统的WiFi密码查询逻辑,无法直接复用netsh相关代码
- Windows环境下按如下要点修改代码:
- 给
subprocess.check_output添加shell=True参数,让系统通过命令行shell自动查找netsh命令位置,规避环境变量导致的路径找不到问题;如果加参数后仍报错,可直接将命令中的netsh替换为完整路径C:\\Windows\\System32\\netsh.exe - 修正参数错误,将
key = clear改为无多余空格的key=clear - 优化字符串截取逻辑,用
strip()替代固定索引切片,避免不同系统语言/版本下输出格式差异导致的截取错误 - 增加系统判断逻辑,非Windows环境直接提示退出,避免无意义报错
- 给
修复后的可运行代码:
import subprocess import os # 非Windows系统直接退出 if os.name != "nt": print("本脚本仅支持在Windows系统上运行") exit() # 拉取所有已保存的WiFi配置文件 meta_data = subprocess.check_output( ["netsh", "wlan", "show", "profiles"], shell=True ) data = meta_data.decode("utf-8", errors="backslashreplace").split("\n") profiles = [] for line in data: if "All User Profile" in line: profile_name = line.split(":")[1].strip() profiles.append(profile_name) print("{:<30}| {:<}".format("Wi-Fi Name", "Password")) print("----------------------------------------------") for profile in profiles: try: results = subprocess.check_output( ["netsh", "wlan", "show", "profile", profile, "key=clear"], shell=True ) results = results.decode("utf-8", errors="backslashreplace").split("\n") password_list = [line.split(":")[1].strip() for line in results if "Key Content" in line] try: print("{:<30}| {:<}".format(profile, password_list[0])) except IndexError: print("{:<30}| {:<}".format(profile, "(无密码/权限不足无法读取)")) except subprocess.CalledProcessError: print("{:<30}| {:<}".format(profile, "读取配置失败"))
补充:如果运行后部分WiFi读不到密码,关闭VS Code后右键选择「以管理员身份运行」,再重新执行脚本即可,部分系统配置需要管理员权限才能读取密钥内容。
内容的提问来源于stack exchange,提问作者Shashwat T.
相关产品推荐
相关产品推荐

