Python 任意系统找回wifi密码

编程入门 行业动态 更新时间:2024-10-28 01:27:06

经常遇到这样一种情况:家里来了客人,问你要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
    )municate()
    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/Ckend/pythondict-tools/tree/master/2.wifi-password

我们的文章到此就结束啦,如果你喜欢我们今天的Python 实战教程,请持续关注我们,如果对你有帮助,麻烦在下面点一个赞/在看哦,有任何问题都可以在下方留言区留言,我们都会耐心解答的!


Python实用宝典

不只是一个宝典

欢迎关注公众号:Python实用宝典

原文来自Python实用宝典:Python 任意系统找回wifi密码

更多推荐

Python 任意系统找回wifi密码

本文发布于:2023-06-14 06:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密码   系统   Python   wifi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!