杰瑞科技汇

Raspbian下Python如何配置WiFi连接?

Of course! Setting up Wi-Fi on a Raspberry Pi running Raspbian (now officially called Raspberry Pi OS) using Python is a common task. There are a few ways to do this, ranging from simple system command calls to more robust library-based approaches.

Raspbian下Python如何配置WiFi连接?-图1
(图片来源网络,侵删)

Let's break down the methods, starting with the most common and straightforward one.


Method 1: Using subprocess to Call wpa_cli (Most Common)

This is the most popular method because it directly interacts with the system's Wi-Fi management daemon (wpa_supplicant). It's reliable and doesn't require any external Python libraries.

How it works: You'll use Python's subprocess module to run the wpa_cli command-line tool, which is designed to configure Wi-Fi connections.

Step-by-Step Guide

  1. Import the subprocess module.
  2. Define your Wi-Fi network details.
  3. Use subprocess.run() to execute the necessary wpa_cli commands.

Here is a complete, commented Python script to connect to a WPA2/WPA3-secured network.

Raspbian下Python如何配置WiFi连接?-图2
(图片来源网络,侵删)
import subprocess
import time
# --- Configuration ---
# Replace with your Wi-Fi network details
SSID = "YourWiFiNetworkName"
PASSWORD = "YourWiFiPassword"
def connect_to_wifi(ssid, password):
    """
    Connects to a Wi-Fi network using wpa_cli.
    """
    print(f"Attempting to connect to {ssid}...")
    # Step 1: Add the new network
    # The 'add_network' command returns a network ID (usually 0 for the first one)
    add_network_cmd = ["sudo", "wpa_cli", "add_network"]
    result = subprocess.run(add_network_cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print("Error adding network:", result.stderr)
        return
    network_id = result.stdout.strip()
    print(f"Successfully added network. ID: {network_id}")
    # Step 2: Set the SSID for the new network
    # We use the network ID from the previous step
    set_ssid_cmd = ["sudo", "wpa_cli", "set_network", network_id, "ssid", f'"{ssid}"']
    subprocess.run(set_ssid_cmd, check=True)
    # Step 3: Set the password (psk for Pre-Shared Key)
    set_psk_cmd = ["sudo", "wpa_cli", "set_network", network_id, "psk", f'"{password}"']
    subprocess.run(set_psk_cmd, check=True)
    # Step 4: Enable the network
    enable_cmd = ["sudo", "wpa_cli", "enable_network", network_id]
    subprocess.run(enable_cmd, check=True)
    # Step 5: Reconfigure wpa_supplicant to apply changes
    # This is a crucial step to make the changes take effect
    reconfigure_cmd = ["sudo", "wpa_cli", "reconfigure"]
    subprocess.run(reconfigure_cmd, check=True)
    print("Wi-Fi configuration sent. Waiting for connection...")
    # Step 6: Check the connection status
    # Loop and check the 'status' command until connected
    max_attempts = 15
    for i in range(max_attempts):
        status_cmd = ["wpa_cli", "status"]
        result = subprocess.run(status_cmd, capture_output=True, text=True)
        if "wpa_state=COMPLETED" in result.stdout:
            print("Successfully connected to Wi-Fi!")
            return True
        time.sleep(2) # Wait 2 seconds before checking again
    print(f"Failed to connect after {max_attempts} attempts.")
    return False
# --- Run the function ---
if __name__ == "__main__":
    connect_to_wifi(SSID, PASSWORD)

How to Run the Script

  1. Save the code above as a Python file (e.g., connect_wifi.py).
  2. Make it executable: chmod +x connect_wifi.py
  3. Run it with sudo: sudo python3 connect_wifi.py
    • Note: sudo is required because wpa_cli needs root privileges to modify system network configurations.

Method 2: Parsing /etc/wpa_supplicant/wpa_supplicant.conf

This method is useful if you want to read existing Wi-Fi configurations or add a new network profile to the configuration file directly.

How it works: You open the wpa_supplicant.conf file, read its contents, add your new network configuration in the correct format, and write it back.

import os
# --- Configuration ---
SSID = "YourWiFiNetworkName"
PASSWORD = "YourWiFiPassword"
CONFIG_FILE = "/etc/wpa_supplicant/wpa_supplicant.conf"
def add_network_to_config(ssid, password, config_path):
    """
    Adds a new network to the wpa_supplicant.conf file.
    """
    network_config = f"""
network={{
    ssid="{ssid}"
    psk="{password}"
}}
"""
    try:
        # Read the current config
        with open(config_path, 'r') as f:
            config_content = f.read()
        # Check if the network already exists to avoid duplicates
        if f'ssid="{ssid}"' in config_content:
            print(f"Network '{ssid}' already exists in the configuration.")
            return
        # Append the new network configuration
        with open(config_path, 'a') as f:
            f.write(network_config)
        print(f"Successfully added network '{ssid}' to {config_path}")
        # Reconfigure wpa_supplicant to apply the changes
        subprocess.run(["sudo", "wpa_cli", "reconfigure"], check=True)
        print("Reconfigured wpa_supplicant.")
    except FileNotFoundError:
        print(f"Error: Configuration file not found at {config_path}")
    except PermissionError:
        print(f"Error: Permission denied. Run the script with 'sudo'.")
    except subprocess.CalledProcessError as e:
        print(f"Error reconfiguring wpa_supplicant: {e}")
# --- Run the function ---
if __name__ == "__main__":
    # This requires subprocess, so let's import it here
    import subprocess
    add_network_to_config(SSID, PASSWORD, CONFIG_FILE)

Important Note: This method is more complex because you have to be careful with the file format. It's generally safer and easier to use wpa_cli as in Method 1, but this approach is good for understanding how the configuration file is structured.


Method 3: Using a Python Library (e.g., pywpa)

For a more "Pythonic" object-oriented approach, you can use a third-party library like pywpa. This abstracts away the command-line calls.

Raspbian下Python如何配置WiFi连接?-图3
(图片来源网络,侵删)

How it works: You install the library and then use its classes and methods to manage Wi-Fi connections.

  1. Install the library:

    pip install pywpa
  2. Use it in your script:

    from pywpa import WPA
    import time
    # --- Configuration ---
    SSID = "YourWiFiNetworkName"
    PASSWORD = "YourWiFiPassword"
    # Create a WPA object
    # Note: This still requires root privileges to function
    wpa = WPA()
    print(f"Attempting to connect to {SSID}...")
    try:
        # Add and enable a network
        network_id = wpa.add_network()
        wpa.set_network(network_id, 'ssid', SSID)
        wpa.set_network(network_id, 'psk', PASSWORD)
        wpa.enable_network(network_id)
        # Re-apply the configuration
        wpa.reconfigure()
        # Check status
        for i in range(15):
            status = wpa.status()
            if status.get('wpa_state') == 'COMPLETED':
                print("Successfully connected to Wi-Fi!")
                break
            time.sleep(2)
        else:
            print("Failed to connect.")
    except Exception as e:
        print(f"An error occurred: {e}")

Summary: Which Method Should You Use?

Method Pros Cons Best For
subprocess + wpa_cli - No external libraries needed
- Direct control over system tools
- Very reliable and standard
- Requires sudo
- Involves shell command knowledge
Most use cases. Quick scripts, automation, and general-purpose Wi-Fi management.
Parsing .conf file - Full control over the config file
- Good for reading/managing existing profiles
- More complex file handling
- Risk of corrupting the config file
Scripts that need to read or programmatically modify the configuration file itself.
Python Library (pywpa) - Clean, object-oriented interface
- Easier to read and maintain
- Adds an external dependency
- May have bugs or not be actively maintained
Projects where you prefer a pure Python API and are comfortable with third-party dependencies.

For most Raspberry Pi projects, Method 1 is the recommended approach. It's the standard, most reliable way to handle Wi-Fi connections from a script.

分享:
扫描分享到社交APP
上一篇
下一篇