
经常遇到这样一种情况:家里来了客人,问你要wifi密码。
尴尬的是,你忘了wifi密码。
不过你的其他设备已经连接过WiFi,这时候你怎么利用这些设备重新获取WiFi密码呢?
有一种方法是登录路由器管理页面,但是如果你连路由器密码也忘了,那就非常尴尬。
还有一种方法是通过iCloud钥匙串,但这个方法非常麻烦,需要通过备份获取。
今天告诉大家一个最简单的方法:通过Python来找回当前使用的wifi密码。
1.准备
开始之前,你要确保Python已经成功安装在电脑上,如果没有,请访问这篇文章:超详细Python安装指南 进行安装。
如果你用Python的目的是数据分析,可以直接安装Anaconda:Python数据分析与挖掘好帮手—Anaconda.
此外,你需要一台已经连接了Wifi的电脑,macOS和windows都可以。
2.原理解析
实质上,获取密码是使用命令的方式,比如Windows下获取WiFi密码:
netsh wlan show profile name=Wifi名称 key=clear | findstr 关键内容
macOS下获取WiFi密码:
sudo security find-generic-password -l wifi名称 -D 'AirPort network password' -w
Linux下获取WiFi密码:
sudo cat /etc/NetworkManager/system-connections/wifi名称| grep psk=
通过这三种命令就可以获取得到当前使用的WiFi名称。
3.代码编写
首先封装命令:
def fetch_password(system, wifi_name):
"""
用于获取命令
Arguments:
system {str} -- 系统类型
wifi_name {str} -- wifi名
Returns:
str -- 密码
Author: Python 实用宝典
"""
if system == "linux":
command = f"sudo cat /etc/NetworkManager/system-connections/{wifi_name}| grep psk="
elif system == "macos":
command = f"sudo security find-generic-password -l{wifi_name} -D 'AirPort network password' -w"
elif system == "windows":
command = f"netsh wlan show profile name={wifi_name} key=clear | findstr 关键内容"
result = fetch_result(system, command)
return result
其中,fetch_result 用于执行命令获得数据:
def fetch_result(system, command):
"""
用于执行命令获取结果
Arguments:
system {str} -- 系统类型
command {str} -- 命令
Returns:
str -- 解码后的密码
Author: Python 实用宝典
"""
result, _ = subprocess.Popen(
command, stdout=subprocess.PIPE, shell=True
).communicate()
return decode_result(system, result)
decode_result用于解码命令:
def decode_result(system, result):
"""
解码密码
Arguments:
system {str} -- [系统类型]
result {str} -- [输出]
Returns:
[str] -- [解码后的密码]
Author: Python 实用宝典
"""
if system == "windows":
# cmd命令得到的结果是bytes型,需要decode
result = result.decode("gb2312")
result = result.strip('\r|\n')
if result != "":
result = result.replace(" ", "")
result = result[result.find(":") + 1:]
result = result[result.find("=") + 1:]
return result
大功告成,你只需要执行:
print(fetch_password('系统类型', 'wifi名称'))
即可获得密码。
如果你的电脑连接过其他wifi,并且没有删除过相关的网络配置,实际上也可以使用该函数获取其他wifi的密码。以上就是完整源代码,如果你懒得再打一遍,可访问github链接获取:
https://github.com/Ckend/pythondict-tools/tree/master/2.wifi-password
我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。
有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。
原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!
Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典

评论(0)