How to List Wi-Fi Networks in Python

Discover how to effortlessly find open Wi-Fi networks around you using Python. This in-depth guide walks you through using OS commands and Python libraries to scan and list available open Wi-Fi networks on both Windows and Linux systems. Perfect for busy urban environments.
  · 9 min read · Updated oct 2023 · Ethical Hacking · Python Standard Library

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

Sometimes, we find ourselves in very busy environments. Environments that have lots of official and commercial buildings around. These kinds of areas often have a lot of Wi-Fi networks in use. Say you’re in need of publically available Wi-Fi, being able to know which is open might be challenging as such areas are usually mixed with both open and secured Wi-Fi. In this article, I'll show you how to write a Python script that would list all open Wi-Fi networks around so it would save you the hassle of manually looking. Also, you’ll learn about some cool OS commands. Grab a cup of coffee and let’s get into it!

Usually, on our computers (regardless of the OS), most of the tasks we click buttons to achieve, actually have OS commands that can be run on the terminal to do the exact same thing. For example, if you want to see all files in a folder, you simply click on the folder. However, if you’re on the terminal, you could simply type the dir command on Windows or ls on Linux. I’m telling you this because the script we’re about to write works based on OS commands.

If you want to make a Wi-Fi scanner using Scapy, then check this tutorial.

Before we go into listing all open Wi-Fi networks, let me show you how to list all Wi-Fi networks within range. Simply open up your terminal or cmd.

If you’re on Windows, type:

$ netsh wlan show networks

On Linux, type:

nmcli device wifi list

These two commands would list all available networks within range. But because we’re programmers and like to automate everything, let’s see how to do this with Python.

Listing All WiFi Networks

We’ll be using Python 3. Any version of Python above 3.6 should do. Open a Python file, name it wifi_networks_lister.py or whatever you like and write this:

import subprocess, platform

# Get the name of the operating system.
os_name = platform.system()
# Check if the OS is Windows.
if os_name == "Windows":
   # Command to list Wi-Fi networks on Windows using netsh.
   list_networks_command = 'netsh wlan show networks'
   # Execute the command and capture the result.
   output = subprocess.check_output(list_networks_command, shell=True, text=True)
   # Print the output, all networks in range.
   print(output)
# Check if the OS is Linux.
elif os_name == "Linux":
   # Command to list Wi-Fi networks on Linux using nmcli.
   list_networks_command = "nmcli device wifi list"
   # Execute the command and capture the output.
   output = subprocess.check_output(list_networks_command, shell=True, text=True)
   # Print the output, all networks in range.
   print(output)
# Handle unsupported operating systems.
else:
   # Print a message indicating that the OS is unsupported (Not Linux or Windows).
   print("Unsupported OS")

In this code, we started by importing subprocess and platform. subprocess is a Python module that allows you to run external system commands, programs, and scripts from within a Python script, providing control over their execution and the ability to capture their output. While the platform module in Python is a standard library module that provides a way to access information about the underlying platform or operating system on which Python is running.

After importing the modules, we checked for the respective OSs and ran the respective commands. Very simple. Run this and your output should be similar to (On Windows):

Observe that there are three networks in range and two of them have their Authentication parameters set to open. 

On Linux:

Listing Open WiFi Networks

Here, notice that similar to the Windows result, there are also three Wi-Fi networks listed. Also, under the security, two have the parameter set to --  this indicates that they are open.  

As programmers, what we can do is run these commands using subprocess and parse the output. i.e try to get the value of the Authentication (on Windows) and Security (on Linux) to determine which networks are open. 

That’s exactly what we’re going to do now. Open up a new Python file, name it whatever you like, and let’s go:

import subprocess, platform, re
from colorama import init, Fore

init()

We start by importing the necessary libraries. We already know what subprocess and platform is used for. re is for working with regular expressions. Regular expressions, often abbreviated as "regex" or "regexp," are powerful tools for pattern matching and text manipulation. 

colorama is used for printing text in different colors. It’s for visual aid and fancy.

init() - is basically initializing colorama. 

Next, we create a function that does the job. i.e. scanning for open Wi-Fi networks:

def list_open_networks():
   # Get the name of the operating system.
   os_name = platform.system()
   # Check if the OS is Windows.
   if os_name == "Windows":
       # Command to list Wi-Fi networks on Windows.
       list_networks_command = 'netsh wlan show networks'
       try:
           # Execute the command and capture the output.
           output = subprocess.check_output(list_networks_command, shell=True, text=True)
           networks = []
           # Parse the output to find open Wi-Fi networks.
           for line in output.splitlines():
               if "SSID" in line:
                   # Extract the SSID (Wi-Fi network name).
                   ssid = line.split(":")[1].strip()
               elif "Authentication" in line and "Open" in line:
                   # Check if the Wi-Fi network has open authentication.
                   networks.append(ssid)
           # Check if any open networks were found.
           if len(networks) > 0:
               # Print a message for open networks with colored output.
               print(f'{Fore.LIGHTMAGENTA_EX}[+] Open Wifi networks in range: \n')
               for each_network in networks:
                   print(f"{Fore.GREEN}[+] {each_network}")
           else:
               # Print a message if no open networks were found.
               print(f"{Fore.RED}[-] No open wifi networks in range")
       except subprocess.CalledProcessError as e:
           # Handle any errors that occur during the execution of the command.
           print(f"{Fore.RED}Error: {e}")
           # Return an empty list to indicate that no networks were found.
           return []

Here, we’re basically checking what OS the code is being executed on. As we saw, different OS’s have different commands for this purpose. Here, the check is for Windows. After getting the results, we access the value of the Authentication. If Authentication and Open are in the same line, this means the network is open. We append all open networks to a list, iterate through the list, and print all open Wi-Fi networks.

Next, we handle the operation, if the OS is Linux: Please bear in mind that this is still in the function we created. Take note of indentation:

    elif os_name == "Linux":
        try:
            # Run nmcli to list available Wi-Fi networks.
            result = subprocess.run(["nmcli", "--fields", "SECURITY,SSID", "device", "wifi", "list"],
                                    stdout=subprocess.PIPE,
                                    text=True, check=True)
            # Access the captured stdout.
            output = result.stdout.strip()
            # Define a regex pattern to capture SSID and Security.
            pattern = re.compile(r'^(?P<security>[^\s]+)\s+(?P<ssid>.+)$', re.MULTILINE)
            # Find all matches in the output.
            matches = pattern.finditer(output)
            # Skip the first match, which is the header.
            next(matches, None)
            print(f"{Fore.LIGHTMAGENTA_EX}[+] Open Wifi networks in range: \n")
            # Loop through all matches (results)
            for match in matches:
                security = match.group('security')
                ssid = match.group('ssid')
                full_match = f"{Fore.GREEN}[+] SSID: {ssid} -------> Security: {security}"
                # Check if the indicator of an open network in our Full match (result).
                if "Security: --" in full_match:
                    print(f"{Fore.GREEN}[+] {ssid}")
                else:
                    print(f"{Fore.RED}[-] No open Wifi networks in range.")
        except subprocess.CalledProcessError as e:
            print(f"Error running nmcli: {e}")
        except Exception as e:
            print(f"An error occurred: {e}")

Here, we’re handling operations for Linux systems. Similar to how we did with Windows. The major difference is the commands (obviously). Also, I used a different method of checking the output here with subprocess. Instead of the check_output() method, I used run(). This is just me showing you different approaches as there are many ways of carrying out programming exercises. Check out the subprocess documentation here.

Finally:

    else:
       print(f"{Fore.RED}Unsupported operating system.")
       return []

# Call the function.
list_open_networks()

If the OS is not Windows or Linux, we tell the user that the OS is not supported as this program is for Windows and Linux. However, using the concepts in this article, users (whose OS is not Windows or Linux) can easily modify or build on the code to work for their OS. All you need is the command to do it and some parsing. 

After running this your output should look like this (on Windows):

On Linux:

Conclusion

There you have it! Now you do not have to go through the hassle of manually searching for open Wi-Fi networks around you. You’re welcome! 

Please note that from a security perspective, open Wi-Fi networks are not encouraged as your data is sent as plain text instead of being encrypted. This means that if hackers intercept your data, they’ll be able to read and use it. This could be your password, banking credentials, etc. I always tell people not to use it, if they can afford not to. If you must use it, consider using a reputable VPN and a plugin called HTTPS everywhere. Stay safe and have a blast!

Get access to the full codes here or here.

Learn also: How to Make a Network Scanner using Scapy in Python.

Happy coding ♥

Just finished the article? Why not take your Python skills a notch higher with our Python Code Assistant? Check it out!

View Full Code Assist My Coding
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!