Home » Tutorials » How to Build a WiFi Scanner in Python

How to Build a WiFi Scanner in Python

Imagine walking through your neighborhood, your device effortlessly connecting to various invisible threads of connectivity. It’s convenient, yes, but it’s also a silent battlefield. Each network represents a fortress, with walls built from passwords and encryption protocols. But how strong are these walls? Are they impregnable shields or merely paper barriers against the siege engines of modern hackers?

Today, we’ll dive into the digital battlefield of Wi-Fi network security by showing you how to build a Wi-Fi scanner using Python, a powerful tool in the cybersecurity arsenal, we’ll learn how to scan Wi-Fi networks and assess their security if they are good or need improvement.

Let’s get started!

Table of Contents

Disclaimer

Please note: before we proceed with this code, I must warn you not to use this code illegally or without consent since it is for educational purposes only.

RELATED:

Imports

We start by importing the subprocess module so we can run commands on our computer’s system. Then we import the re module which can find specific words or phrases by using patterns to search through text.

After that, we import the sys module to use some basic system functionality. 

import subprocess
import re
import sys

scan_wifi_networks Function

Next, we define our functions, we start with the Scan Wi-Fi function. This function works in two parts:

The first part is finding out the operating system (Windows, Linux, macOS) using the sys module.

The second one is executing the appropriate command to scan the Wi-Fi using the subprocess module which also handles any error that may occur during the scanning process, and by the end it returns all the Wi-Fi networks found in the area and their encryptions (wep, wpa, tkip) to the main function.

def scan_wifi_networks():
   """Scan for available Wi-Fi networks."""
   try:
       print("Scanning for Wi-Fi networks...")
       if sys.platform.startswith('win'):
           result = subprocess.check_output(['netsh', 'wlan', 'show', 'network'])
       elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
           result = subprocess.check_output(['iwlist', 'scan'])
       else:
           print("Unsupported platform")
           return


       return result.decode('utf-8')
   except subprocess.CalledProcessError as e:
       print(f"Error: Unable to scan Wi-Fi networks. {e}")
       return None
   except Exception as e:
       print(f"Error: {e}")
       return None

analyze_network_security Function

After that, we create this one that evaluates the security of each Wi-Fi network found by the previous function, then it gives feedback if the security is strong or not and gives advice if needed by printing them.

def analyze_network_security(ssid, encryption_type):
   """Analyze the security of a Wi-Fi network."""
   try:
       print(f"Analyzing security for network: {ssid}")
       # Check if encryption type is weak or vulnerable
       if encryption_type.lower() in ['wep', 'wpa', 'tkip']:
           print("Warning: Weak encryption type detected.")
           print("Advice: Consider upgrading to WPA2 or WPA3 for stronger security.")
       else:
           print("Security: Strong")
           print("Advice: Keep your Wi-Fi password strong and secure, and regularly update your router firmware.")
       # You can add more checks for specific vulnerabilities here
   except Exception as e:
       print(f"Error: {e}")

Defining Main Function

Now we define the heart of the script, this one ensures that each function does its job in a smooth manner. When the user runs the script this function calls the scan_wifi_networks () function to extract encryptions of each Wi-Fi network, so it can pass those encryptions to the analyze_network_security () function to give its feedback.

def main():
   wifi_scan_result = scan_wifi_networks()
   if wifi_scan_result:
       print("\nWi-Fi scan result:")
       print(wifi_scan_result)
       networks = re.findall(r'SSID\s\d+\s:\s(.+)', wifi_scan_result)
       for ssid in networks:
           print(f"\nSSID: {ssid}")
           encryption_match = re.search(r'Encryption\s*:\s(.+)', wifi_scan_result)
           if encryption_match:
               encryption_type = encryption_match.group(1).strip()
               print(f"Encryption Type: {encryption_type}")
               analyze_network_security(ssid, encryption_type)
           else:
               print("Error: Unable to retrieve encryption type.")
   else:
       print("No Wi-Fi networks found or error occurred during scanning.")

Main Block

if __name__ == "__main__":
   main()

What this part does is basically tell the main function that you’re allowed to function only if the script is run directly, if it is imported as a module you will not function, therefore rendering the script useless in that case.

Example

Full Code

import subprocess
import re
import sys


def scan_wifi_networks():
   """Scan for available Wi-Fi networks."""
   try:
       print("Scanning for Wi-Fi networks...")
       if sys.platform.startswith('win'):
           result = subprocess.check_output(['netsh', 'wlan', 'show', 'network'])
       elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
           result = subprocess.check_output(['iwlist', 'scan'])
       else:
           print("Unsupported platform")
           return


       return result.decode('utf-8')
   except subprocess.CalledProcessError as e:
       print(f"Error: Unable to scan Wi-Fi networks. {e}")
       return None
   except Exception as e:
       print(f"Error: {e}")
       return None


def analyze_network_security(ssid, encryption_type):
   """Analyze the security of a Wi-Fi network."""
   try:
       print(f"Analyzing security for network: {ssid}")
       # Check if encryption type is weak or vulnerable
       if encryption_type.lower() in ['wep', 'wpa', 'tkip']:
           print("Warning: Weak encryption type detected.")
           print("Advice: Consider upgrading to WPA2 or WPA3 for stronger security.")
       else:
           print("Security: Strong")
           print("Advice: Keep your Wi-Fi password strong and secure, and regularly update your router firmware.")
       # You can add more checks for specific vulnerabilities here
   except Exception as e:
       print(f"Error: {e}")


def main():
   wifi_scan_result = scan_wifi_networks()
   if wifi_scan_result:
       print("\nWi-Fi scan result:")
       print(wifi_scan_result)
       networks = re.findall(r'SSID\s\d+\s:\s(.+)', wifi_scan_result)
       for ssid in networks:
           print(f"\nSSID: {ssid}")
           encryption_match = re.search(r'Encryption\s*:\s(.+)', wifi_scan_result)
           if encryption_match:
               encryption_type = encryption_match.group(1).strip()
               print(f"Encryption Type: {encryption_type}")
               analyze_network_security(ssid, encryption_type)
           else:
               print("Error: Unable to retrieve encryption type.")
   else:
       print("No Wi-Fi networks found or error occurred during scanning.")


if __name__ == "__main__":
   main()

Happy Coding!

2 thoughts on “How to Build a WiFi Scanner in Python”

  1. community classifieds USA

    Sweet blog! I found it while surfing around on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!
    Many thanks

    1. Thanks for your feedback! For getting listed on Yahoo News, focus on maintaining your original, high-quality content and ensure it’s SEO-optimized. While direct submission isn’t an option, being consistent and engaging might catch the attention of news aggregators over time. Keep up the great work!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top