How to connect WiFi using Python?
Published on Aug. 22, 2023, 12:15 p.m.
There are multiple ways to connect to a Wi-Fi network using Python, but one common way is to use the subprocess
module to execute command line arguments related to Wi-Fi connection for the operating system used. Here is an example for Windows using netsh
command:
import subprocess
# Configure Wi-Fi network settings
ssid = "example_network"
password = "example_password"
command = "netsh wlan add profile filename=\"{}\"".format(ssid)
args = ["keyMaterial={}".format(password)]
result = subprocess.run(command, capture_output=True, input="\n".join(args), encoding="cp1252")
# Connect to Wi-Fi network
command = "netsh wlan connect name=\"{}\"".format(ssid)
result = subprocess.run(command, capture_output=True, encoding="cp1252")
# Check status of Wi-Fi connection
command = "netsh wlan show interfaces"
result = subprocess.run(command, capture_output=True, encoding="cp1252")
print(result.stdout)
This example sets up a new Wi-Fi network with the given SSID and password using the netsh wlan add profile
command. Then, it connects to that network using netsh wlan connect
. Finally, it checks the status of the connection by running netsh wlan show interfaces
.
Note that this example is specifically for Windows, and the commands used to configure and connect to a Wi-Fi network may be different on other operating systems. Also, this code run as admin so if you encounter access denied
errors you need to run the script with admin privileges.