Tuesday, 17 October 2023

Building a Wi-Fi Scanner with Python

Whether you're a network administrator or just curious about Wi-Fi networks around you, a Wi-Fi scanner can provide invaluable insights. In this blog post, we'll walk you through creating a simple yet effective Wi-Fi scanner using Python, and we'll even show you example output to give you a sense of what you'll achieve.

Requirements

Before diving into the code, make sure you have:

  • Python installed on your system
  • The pywifi Python library for Wi-Fi interaction

To install pywifi, open your terminal and type:

pip install pywifi

Getting Started

Let's kick off by importing the pywifi library and initializing it.

from pywifi import PyWiFi, const
wifi = PyWiFi()

Selecting an Interface

To scan Wi-Fi networks, you need to choose a Wi-Fi interface to work with. Usually, your machine has at least one.

iface = wifi.interfaces()[0]  # Picking the first available interface

Initiating the Scan

To initiate the scanning process, simply run:

iface.scan()

Since it takes a few seconds for the scan to complete, it's best to wait before fetching the results.

import time
time.sleep(2)  # Wait for scan to complete
scan_results = iface.scan_results()

Displaying Results

Now let's display the relevant details of each Wi-Fi network.

for network in scan_results:
    print(f"SSID: {network.ssid}, Signal: {network.signal}, Security: {const.AUTH_ALG_DICT.get(network.akm[0], 'Unknown')}")

Example Output

When you run the script, you should see output similar to this:

SSID: HomeNetwork, Signal: -45, Security: WPA2PSK
SSID: CoffeeShopWiFi, Signal: -60, Security: OPEN
SSID: Office_Net, Signal: -50, Security: WPA2PSK

Complete Script

Here's how you can put it all together:

from pywifi import PyWiFi, const
import time

def scan_wifi():
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]
    iface.scan()

    time.sleep(2)
    scan_results = iface.scan_results()

    for network in scan_results:
        print(f"SSID: {network.ssid}, Signal: {network.signal}, Security: {const.AUTH_ALG_DICT.get(network.akm[0], 'Unknown')}")

if __name__ == "__main__":
    scan_wifi()

Building a Wi-Fi scanner in Python is relatively straightforward, thanks to the pywifi library. This basic example can serve as a foundation for more advanced projects, like sorting networks by signal strength or adding additional functionalities.

No comments:

Post a Comment