python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python提取连接过WiFi名称密码

使用Python提取本机连接过WiFi名称和密码

作者:flysh05

本文介绍如何在Windows系统上用Python获取历史连接过的WiFi名称及密码并导出为CSV文件,通过调用netsh wlan show profiles获取WiFi列表,再使用netsh wlan show profile命令解析各WiFi密码,需要的朋友可以参考下

在 Windows 系统上用Python 获取当前电脑之前接过的 WiFi 名称及密码,并导出csv文件。

实现原理

Windows 会把所有连接过的 WiFi 配置保存在系统中,使用命令:

Python 只需要调用这些命令并解析即可。

Python 代码如下

# -*- coding: utf-8 -*-
import subprocess
import re
import csv
import sys

def run_cmd(cmd):
    """执行系统命令并返回输出(永不返回 None)"""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            encoding="gbk",
            errors="ignore"
        )
        return result.stdout or ""
    except Exception as e:
        return ""

def get_wifi_list():
    """获取所有 WiFi 配置名称(兼容中英文系统)"""
    output = run_cmd("netsh wlan show profiles")

    # 兼容中文:所有用户配置文件
    # 兼容英文:All User Profile
    profiles = re.findall(
        r"(?:所有用户配置文件|All User Profile)\s*:\s*(.*)",
        output
    )

    return [p.strip() for p in profiles]

def get_wifi_password(name):
    """获取指定 WiFi 的密码(兼容中英文系统)"""
    if not name:
        return ""

    output = run_cmd(f'netsh wlan show profile name="{name}" key=clear')

    # 兼容中文:关键内容
    # 兼容英文:Key Content
    match = re.search(
        r"(?:关键内容|Key Content)\s*:\s*(.*)",
        output
    )

    return match.group(1).strip() if match else ""

def export_wifi_passwords(csv_file="wifi_passwords.csv"):
    """导出所有 WiFi 名称与密码到 CSV,并打印到 stdout(供 C# 调用)"""
    wifi_list = get_wifi_list()
    data = []

    for wifi in wifi_list:
        pwd = get_wifi_password(wifi)
        data.append([wifi, pwd])
        print(f"{wifi} : {pwd}")

    # 写入 CSV 文件
    try:
        with open(csv_file, "w", newline="", encoding="utf-8-sig") as f:
            writer = csv.writer(f)
            writer.writerow(["WiFi 名称", "密码"])
            # writer.writerows(data)
            for wifi, pwd in data:
                writer.writerow([wifi, "\t" + pwd]) # 把它当成纯文本,不会吞掉前导 0
                # writer.writerow([wifi, f"'{pwd}"])

    except Exception as e:
        print(f"写入 CSV 文件失败: {e}")

    sys.stdout.flush()  # 关键:确保 C# 能读取完整输出

if __name__ == "__main__":
    export_wifi_passwords()

运行效果

终端输出:

WXzhongshuge : 20130423
Ritchie : ritchie12345678
KFC FREE WIFI : 
ChinaNet-Starbucks : 
RD_Meeting_Room : 57744789
1205 : W136444564
高铁WiFi : 
CMCC-JJJ2 : 12345678
H3C_E4C764 : 6575754635

已导出到文件:wifi_passwords.csv

注意事项

以上就是使用Python提取本机连接过WiFi名称和密码的详细内容,更多关于Python提取连接过WiFi名称密码的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文