如何使用Python获取Wifi密码(附代码)

1,070 阅读2分钟

在我们之前的Python教程中,我们已经用Python开发了蛇形游戏。在本教程中,我们将解释如何用Python获取保存的WiFi密码。

在与多个设备连接时,我们有时会忘记密码。因此,在这里我们将解释如何轻松获得所有保存的WIFI密码和连接细节。

通过Python,你可以使用subprocess 模块轻松获得保存的WIFI密码细节。该模块允许通过在我们的Python程序中运行netsh 命令来检查连接的WIFI密码。

因此,让我们开始编写代码来获取Wifi密码。

检查连接的WIFI密码的命令

有两个命令需要运行以获得保存的Wifi密码的细节:

netsh wlan show profile
netsh wlan show profile PROFILE-NAME key=clear

第一条命令返回连接的WIFI的配置文件,第二条命令显示连接的WIFI密码。

执行获取Wifi密码

我们将导入subprocess 模块,在我们的python程序中运行cmd命令。

我们将使用该模块中的函数check_output () 来运行这两个命令并获得配置文件数据:

import subprocess

data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')

我们将把资料数据转换为列表:

allProfiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]

我们将循环浏览个人资料列表并检查密码:

for i in allProfiles:
    results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 
                        'key=clear']).decode('utf-8').split('\n')
	results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]

最后,检查并存储密码,并在try...except中打印:

try:
        print ("{:<30}|  {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}|  {:<}".format(i, ""))

Complete code to get Wifi Passwords

Here is complete code to get saved Wifi passwords on a computer:

#wifi.py

import subprocess

data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')

allProfiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]

for i in allProfiles:
    results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 
                        'key=clear']).decode('utf-8').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, ""))

Output:

web_logic_1                   |  web@#fgh@1
web_tuts                      |  mypass@Wlm#
OnePlus            	      |  wifi@pass#$
TP-Link                       |  tp@my#1
my magic                      |  my@top#1
dingding                      |  ding@jk1#@!