Windows下通过Python获取链接过的WIFI密码
原理是自动化"netsh wlan show profiles"的查询过程,后通过正则匹配获取
1 # subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值 2 import subprocess 3 import re 4 5 # 用于判断OS的语言 6 import locale 7 loc_lang = locale.getdefaultlocale() 8 # print(loc_lang[0]) 9 10 # 代码中用到的正则匹配模式字符串,提取出来以便不同语言系统使用,默认支持中文英文,其他语言需要更改匹配语句 11 if loc_lang[0] == "zh_CN": 12 re_pattern = ["所有用户配置文件 : (.*)\r", "安全密钥 : 不存在", "关键内容 : (.*)\r"] 13 else: 14 re_pattern = ["All User Profile : (.*)\r", "Security key : Absent", "Key Content : (.*)\r"] 15 16 # 如果 capture_output 设为 true,stdout 和 stderr 将会被捕获 17 cmd_output = subprocess.run(["netsh", "wlan", "show", "profiles"], capture_output=True).stdout.decode('gbk') 18 # print(cmd_output) 19 wifi_names = (re.findall(re_pattern[0], cmd_output)) 20 # print(wifi_names) 21 wifi_list = [] 22 if len(wifi_names) != 0: 23 for name in wifi_names: 24 # 每一个wifi的信息存储在一个字典里 25 wifi_profile = {} 26 profile_info = subprocess.run(["netsh", "wlan", "show", "profiles", name], 27 capture_output=True).stdout.decode('gbk') 28 # print(profile_info) 29 # 判断wifi密码是否存储在windows计算机里,不存在则忽略 30 if re.search(re_pattern[1], profile_info): 31 continue 32 else: 33 wifi_profile["ssid"] = name 34 # 密码存在时,加上命令参数“key=clear”显示wifi密码 35 profile_info_pass = subprocess.run(["netsh", "wlan", "show", "profiles", name, "key=clear"], 36 capture_output=True).stdout.decode('gbk') 37 password = re.search(re_pattern[2], profile_info_pass) 38 # print(password) 39 if not password: 40 wifi_profile["password"] = None 41 else: 42 wifi_profile["password"] = password[1] 43 wifi_list.append(wifi_profile) 44 45 for i in range(len(wifi_list)): 46 print(wifi_list[i])