Home » Tutorials » How to Extract Saved WiFi Passwords in Python

How to Extract Saved WiFi Passwords in Python

Today’s journey is a digital treasure hunt where Python is our magic key! We’re not just sneaking around; we’re diving deep into Python’s wonders and seeing how it plays with various operating systems.

In this tutorial, we’ll show you the easy steps to extract saved Wi-Fi passwords on any device using Python, whether it’s Windows, macOS, or Linux. Let’s dive right in!

Table of Contents

Disclaimer

Before we dive into extracting Wi-Fi passwords using Python. Apply the techniques on networks and devices you own or have explicit permission to use. Unauthorized access is illegal and unethical. Use your skills responsibly.

Imports

We start by importing the subprocess module, which allows us to run system commands from within Python, then we import re module that provides support for regular expressions.

After, we import the platform module which gives information about the operating system on which the script is running.

import subprocess
import re
import platform

get_wifi_passwords Function

As the title suggests, this function retrieves Wi-Fi passwords. Initially, it determines the operating system using platform.system(). Then, it initializes an empty list named passwords to store the retrieved passwords. The function adapts to the operating system (Windows, Linux, macOS) to begin the retrieval process.

If any errors occur during this process, they are printed out. Once the operation successfully completes, the passwords list, previously empty, is filled with Wi-Fi passwords, ready to be displayed.

def get_wifi_passwords():
   system = platform.system()
   passwords = {}
   try:
       if system == 'Windows':
           result = subprocess.run(['netsh', 'wlan', 'show', 'profiles'], capture_output=True, text=True, check=True)
           profiles = re.findall(r'All User Profile\s*:\s*(.*)', result.stdout)
           for profile in profiles:
               profile_result = subprocess.run(['netsh', 'wlan', 'show', 'profile', profile, 'key=clear'], capture_output=True, text=True, check=True)
               if "Key Content" in profile_result.stdout:
                   password_line = [line.strip() for line in profile_result.stdout.splitlines() if "Key Content" in line][0]
                   password = password_line.split(":")[1].strip()
                   passwords[profile] = password
       elif system == 'Linux':
           result = subprocess.run(['nmcli', 'connection', 'show', '--active'], capture_output=True, text=True, check=True)
           connections = re.findall(r'(\S+)\s+\S+\s+\S+\s+wifi\s+\S+\s+(\S+)', result.stdout)
           for connection in connections:
               ssid = connection[0]
               password_result = subprocess.run(['nmcli', 'connection', 'show', 'id', ssid, 'wifi.secrets'], capture_output=True, text=True, check=True)
               if "password:" in password_result.stdout:
                   password = re.search(r'password: (.+)', password_result.stdout).group(1)
                   passwords[ssid] = password
       elif system == 'Darwin':  # macOS
           result = subprocess.run(['/usr/sbin/security', 'find-generic-password', '-ga', 'WIFI'], capture_output=True, text=True, check=True)
           password = re.search(r'password: "(.*)"', result.stdout).group(1)
           passwords["Wi-Fi"] = password
       else:
           print("Unsupported operating system.")
   except Exception as e:
       print("Error:", e)
   return passwords

Now, let’s delve a little deeper into how this function retrieves passwords from each operating system.

Extracting Wi-Fi Passwords for Windows

As mentioned earlier, this function retrieves passwords based on the operating system. In this section, we’ll explore how it operates specifically on Windows. Initially, once the operating system is identified as Windows, the function employs subprocess.run() to execute netsh wlan show profiles. This command extracts the names of Wi-Fi profiles, which are then stored in a list named profiles.

Following this, the function iterates through each Wi-Fi profile. For each profile, it uses the netsh command again, but this time to retrieve the password associated with that profile. These passwords are then stored in the passwords list, completing the retrieval process.

       if system == 'Windows':
           result = subprocess.run(['netsh', 'wlan', 'show', 'profiles'], capture_output=True, text=True, check=True)
           profiles = re.findall(r'All User Profile\s*:\s*(.*)', result.stdout)
           for profile in profiles:
               profile_result = subprocess.run(['netsh', 'wlan', 'show', 'profile', profile, 'key=clear'], capture_output=True, text=True, check=True)
               if "Key Content" in profile_result.stdout:
                   password_line = [line.strip() for line in profile_result.stdout.splitlines() if "Key Content" in line][0]
                   password = password_line.split(":")[1].strip()
                   passwords[profile] = password

Extracting Wi-Fi Passwords for Linux

Now, in the case of the operating system being Linux, the process follows similarly to that on Windows but with some modifications. Instead of using netsh, it utilizes nmcli to extract the Wi-Fi profile names and retrieve their passwords, which are then stored in the passwords list.

       elif system == 'Linux':
           result = subprocess.run(['nmcli', 'connection', 'show', '--active'], capture_output=True, text=True, check=True)
           connections = re.findall(r'(\S+)\s+\S+\s+\S+\s+wifi\s+\S+\s+(\S+)', result.stdout)
           for connection in connections:
               ssid = connection[0]
               password_result = subprocess.run(['nmcli', 'connection', 'show', 'id', ssid, 'wifi.secrets'], capture_output=True, text=True, check=True)
               if "password:" in password_result.stdout:
                   password = re.search(r'password: (.+)', password_result.stdout).group(1)
                   passwords[ssid] = password

Extracting Wi-Fi Passwords for macOS

In the case of the macOS operating system, the function will use /usr/sbin/security, find-generic-password, -ga, WIFI in combination with subprocess.run() to retrieve the passwords of the Wi-Fi profiles and store them in the passwords list.

       elif system == 'Darwin':  # macOS
           result = subprocess.run(['/usr/sbin/security', 'find-generic-password', '-ga', 'WIFI'], capture_output=True, text=True, check=True)
           password = re.search(r'password: "(.*)"', result.stdout).group(1)
           passwords["Wi-Fi"] = password

Handling Unsupported Operating Systems

Then, imagine you’re all set to run your Python script, only to discover that your operating system isn’t supported. Frustrating, right? To prevent this scenario, our code includes a clever safeguard:

If the operating system is neither Windows, Linux, nor macOS, it won’t leave you guessing. Instead, it immediately prints an error message, letting you know that your system isn’t compatible. This little detail not only saves you time but also prevents any head-scratching moments. By anticipating this issue, we ensure a smooth experience and clear communication, even when things don’t go as planned.

       else:
           print("Unsupported operating system.")
   except Exception as e:
       print("Error:", e)
   return passwords

Printing the Extracted Wi-Fi Passwords

Lastly, if the list of passwords, filled by the get_wifi_passwords() function, is not empty, it will be displayed. However, if the list remains empty, indicating that no passwords were retrieved, a message stating that “No saved Wi-Fi passwords found” will be printed. This ensures users are always informed about the status of their Wi-Fi password retrieval.

passwords = get_wifi_passwords()
if passwords:
   print("Saved Wi-Fi passwords:")
   for ssid, password in passwords.items():
       print(f"SSID: {ssid}, Password: {password}")
else:
   print("No saved Wi-Fi passwords found.")

Example

Full Code

import subprocess
import re
import platform


def get_wifi_passwords():
   system = platform.system()
   passwords = {}
   try:
       if system == 'Windows':
           result = subprocess.run(['netsh', 'wlan', 'show', 'profiles'], capture_output=True, text=True, check=True)
           profiles = re.findall(r'All User Profile\s*:\s*(.*)', result.stdout)
           for profile in profiles:
               profile_result = subprocess.run(['netsh', 'wlan', 'show', 'profile', profile, 'key=clear'], capture_output=True, text=True, check=True)
               if "Key Content" in profile_result.stdout:
                   password_line = [line.strip() for line in profile_result.stdout.splitlines() if "Key Content" in line][0]
                   password = password_line.split(":")[1].strip()
                   passwords[profile] = password
       elif system == 'Linux':
           result = subprocess.run(['nmcli', 'connection', 'show', '--active'], capture_output=True, text=True, check=True)
           connections = re.findall(r'(\S+)\s+\S+\s+\S+\s+wifi\s+\S+\s+(\S+)', result.stdout)
           for connection in connections:
               ssid = connection[0]
               password_result = subprocess.run(['nmcli', 'connection', 'show', 'id', ssid, 'wifi.secrets'], capture_output=True, text=True, check=True)
               if "password:" in password_result.stdout:
                   password = re.search(r'password: (.+)', password_result.stdout).group(1)
                   passwords[ssid] = password
       elif system == 'Darwin':  # macOS
           result = subprocess.run(['/usr/sbin/security', 'find-generic-password', '-ga', 'WIFI'], capture_output=True, text=True, check=True)
           password = re.search(r'password: "(.*)"', result.stdout).group(1)
           passwords["Wi-Fi"] = password
       else:
           print("Unsupported operating system.")
   except Exception as e:
       print("Error:", e)
   return passwords


passwords = get_wifi_passwords()
if passwords:
   print("Saved Wi-Fi passwords:")
   for ssid, password in passwords.items():
       print(f"SSID: {ssid}, Password: {password}")
else:
   print("No saved Wi-Fi passwords found.")

Happy Coding!

Learn also: How to Build a WiFi Scanner in Python

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

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

Scroll to Top
×