To create a Python script that checks for a Wi-Fi connection and connects to a Wi-Fi network if there isn't one, you can use a combination of the Python subprocess module to interact with the Windows Command Prompt, and Windows command-line tools like netsh.
Here's a simple Python script that uses netsh to check the Wi-Fi status and connects to a predefined Wi-Fi network if it's not connected. This script assumes you already have the Wi-Fi profile for the network you want to connect to saved on your computer.
import subprocess
import re
import time
# Define the SSID of your WiFi network
wifi_ssid = "YourWiFiSSID"
wifi_password = "YourWiFiPassword"
def check_wifi_connected():
"""Check if the computer is currently connected to a Wi-Fi network."""
result = subprocess.run(['netsh', 'wlan', 'show', 'interfaces'], capture_output=True, text=True)
# Look for the SSID in the command output
return re.search(r'SSID\s+:\s+{}'.format(wifi_ssid), result.stdout) is not None
def connect_to_wifi(ssid, password):
"""Attempt to connect to the specified Wi-Fi network."""
print(f"Connecting to {ssid}...")
subprocess.run(['netsh', 'wlan', 'connect', f'name={ssid}', f'ssid={ssid}', f'key={password}'])
# Check if the computer is connected to the specified Wi-Fi network
if check_wifi_connected():
print(f"Already connected to {wifi_ssid}.")
else:
print(f"Not connected to {wifi_ssid}. Attempting to connect...")
connect_to_wifi(wifi_ssid, wifi_password)
# Wait a few seconds and check the connection again
time.sleep(5)
if check_wifi_connected():
print(f"Successfully connected to {wifi_ssid}.")
else:
print(f"Failed to connect to {wifi_ssid}.")
Here are a few things to note:
- Replace
"YourWiFiSSID" and "YourWiFiPassword" with the SSID and password of your network.
- This script assumes that the network profile is already saved on your computer. If it’s not, you need to save the profile first, or you can configure the network via the command line or GUI.
- Windows Wi-Fi management via
netsh might require administrator privileges. You may need to run this script as an administrator.
- The
check_wifi_connected function looks for the SSID in the output of netsh wlan show interfaces to determine if it's connected.
- The
connect_to_wifi function attempts to connect to the Wi-Fi network using the details provided. The netsh wlan connect command requires the name of the Wi-Fi profile, which should be the same as the SSID by default.
- The script includes a brief pause after attempting to connect, as it can take a few seconds for the connection to be established.
Remember that programmatically connecting to a Wi-Fi network can introduce security risks, so ensure you're following best practices for managing credentials and network information within your scripts.