读取 Windows 系统上已保存的无线网络(Wi-Fi)密码的 Python 程序。

这个新程序将执行以下操作:
  1. 调用 Windows 系统的 netsh wlan show profiles 命令,获取所有保存过的 Wi-Fi 网络名称。
  1. 遍历每一个网络名称,使用 netsh wlan show profile name="网络名称" key=clear 命令来获取其详细信息,其中会包含明文密码。
  1. 解析命令返回的结果,提取出网络名称和对应的密码。
  1. 将所有找到的网络和密码清晰地打印出来。

这个程序将主要依赖 Python 内置的 subprocess 和 re 模块,无需安装任何第三方库。

 

import subprocess
import re
import sys


def get_wifi_passwords():
"""获取 Windows 系统上所有已保存的 WiFi 密码"""

if sys.platform != 'win32':
print("此脚本仅支持在 Windows 上运行。")
return None

wifi_passwords = {}

# 尝试使用 'gbk' 解码,这在中文 Windows 系统上很常见。
# 如果你的系统语言不是中文,可能需要改成 'utf-8' 或其他编码。
encoding = 'gbk'

try:
# 1. 获取所有WiFi配置文件的输出
profiles_output = subprocess.run(
['netsh', 'wlan', 'show', 'profiles'],
capture_output=True,
text=True,
check=True,
encoding=encoding,
errors='ignore'
).stdout

# 2. 根据系统语言确定正则表达式
if "所有用户配置文件" in profiles_output:
profile_name_re = r"所有用户配置文件\s*:\s*(.*)"
password_re = r"关键内容\s*:\s*(.*)"
else:
# 默认使用英文匹配
profile_name_re = r"All User Profile\s*:\s*(.*)"
password_re = r"Key Content\s*:\s*(.*)"

profile_names = [name.strip() for name in re.findall(profile_name_re, profiles_output)]

# 3. 遍历每个配置文件,获取密码
for name in profile_names:
try:
profile_info_output = subprocess.run(
['netsh', 'wlan', 'show', 'profile', f'name="{name}"', 'key=clear'],
capture_output=True,
text=True,
check=True,
encoding=encoding,
errors='ignore'
).stdout

password_match = re.search(password_re, profile_info_output)

if password_match:
wifi_passwords[name] = password_match.group(1).strip()
else:
wifi_passwords[name] = "无密码"
except subprocess.CalledProcessError:
wifi_passwords[name] = "无法获取密码"

except subprocess.CalledProcessError as e:
print(f"执行 'netsh' 命令失败: {e}")
print("提示:请尝试以管理员权限运行此脚本。")
return None
except FileNotFoundError:
print("未找到 'netsh' 命令。此脚本仅适用于 Windows 操作系统。")
return None

return wifi_passwords


if __name__ == "__main__":
print("正在读取系统中已保存的无线网络密码...")

found_passwords = get_wifi_passwords()

if found_passwords is not None:
if found_passwords:
print("\n" + "=" * 40)
print(" 已找到的WiFi密码 ")
print("=" * 40)

# 为了美观地对齐输出,计算最长的网络名称长度
max_name_len = 0
if found_passwords:
max_name_len = max(len(name) for name in found_passwords.keys())

for name, password in found_passwords.items():
print(f" 网络: {name:<{max_name_len}} 密码: {password}")
print("=" * 40)
else:
print("\n未在系统中找到任何已保存的无线网络配置文件。")
else:
print("\n获取密码失败。请检查是否在 Windows 环境下并拥有足够权限。")

 

posted @ 2025-07-16 16:35  Token007  阅读(83)  评论(0)    收藏  举报