从Python在Linux上连接受保护的WiFi

12 投票
1 回答
11150 浏览
提问于 2025-04-17 16:38

我正在为Ubuntu Linux开发一个软件,需要连接到WiFi接入点。这个WiFi网络不是固定的,可能在软件运行期间多次变化(用户可以随时要求更改)。我的想法是:给定一组SSID和它们的WPA或WEP密码,软件应该能够随意切换网络,而不需要在系统中的任何配置文件里做改动。

目前遇到的最大问题似乎是如何将密码传递给连接。到目前为止,我的操作环境是这样的:

  • 一台装有WiFi适配器的Ubuntu 12.10机器。
  • 使用Python来运行软件,并请求连接。
  • connman 0.79版本。
  • wpa_supplicant v1.0版本。
  • d-bus。

起初我以为可以通过d-bus将密码传递给connman,但这个版本的connman和1.11版本似乎都没有提供这样的方式。后来我发现可以在/var/lib/connman/目录下生成一个service_<SSID>.conf文件。这个文件的内容非常简单,像这样:

[service_SSID]
Type=wifi
Name=Network-SSID
Passphrase=here-goes-the-passphrase

一旦这个文件创建完成,连接到网络只需要在相应的服务中简单调用net.connman.Service.Connect()方法。问题是,connman不会解析这个配置文件,除非它被重启。这需要sudo权限,额外的时间,并且增加了“现在可能出什么问题”的风险。然后我想到了可以通过某种方式将密码传递给wpa_supplicant的d-bus API,但我没有找到任何相关的信息。

在谷歌搜索中也没有找到有用的结果。感觉好像没有人尝试过这样做。

命令sudo iwconfig wlan0 essid <SSID> key s:<PASSPHRASE>会导致SET failed on device wlan0 ; Invalid argument.的错误。而且,这个命令也需要sudo权限,我希望能避免使用。

我试着弄清楚wpa_gui程序是怎么实现的。首先我发现它也需要sudo,并且它直接向/var/run/wpa_supplicant/wlan0发送了一堆命令。如果我找不到更简单的方法,复制这种行为将是我的最后选择。

所以,关键问题是:如何使用Python连接到一个WEP/WPA保护的WiFi网络?
我也在想使用connman是否是个好方法,或者我应该回到Ubuntu默认的网络管理器。

1 个回答

10

这段内容讲的是如何在WPA网络下进行设置。

首先,建议你放弃使用connman,改用NetworkManager。下面的示例脚本展示了如何启用无线网络支持,检查是否有指定SSID的网络可用,使用WPA密码连接到这个SSID,然后再断开网络并禁用无线功能。我觉得这个脚本还有改进的空间,但目前这个版本已经足够用作示例了:

#!/usr/bin/python

# This script shows how to connect to a WPA protected WiFi network
# by communicating through D-Bus to NetworkManager 0.9.
#
# Reference URLs:
# http://projects.gnome.org/NetworkManager/developers/
# http://projects.gnome.org/NetworkManager/developers/settings-spec-08.html

import dbus
import time

SEEKED_SSID = "skynet"
SEEKED_PASSPHRASE = "qwertyuiop"

if __name__ == "__main__":
    bus = dbus.SystemBus()
    # Obtain handles to manager objects.
    manager_bus_object = bus.get_object("org.freedesktop.NetworkManager",
                                        "/org/freedesktop/NetworkManager")
    manager = dbus.Interface(manager_bus_object,
                             "org.freedesktop.NetworkManager")
    manager_props = dbus.Interface(manager_bus_object,
                                   "org.freedesktop.DBus.Properties")

    # Enable Wireless. If Wireless is already enabled, this does nothing.
    was_wifi_enabled = manager_props.Get("org.freedesktop.NetworkManager",
                                         "WirelessEnabled")
    if not was_wifi_enabled:
        print "Enabling WiFi and sleeping for 10 seconds ..."
        manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled",
                          True)
        # Give the WiFi adapter some time to scan for APs. This is absolutely
        # the wrong way to do it, and the program should listen for
        # AccessPointAdded() signals, but it will do.
        time.sleep(10)

    # Get path to the 'wlan0' device. If you're uncertain whether your WiFi
    # device is wlan0 or something else, you may utilize manager.GetDevices()
    # method to obtain a list of all devices, and then iterate over these
    # devices to check if DeviceType property equals NM_DEVICE_TYPE_WIFI (2).
    device_path = manager.GetDeviceByIpIface("wlan0")
    print "wlan0 path: ", device_path

    # Connect to the device's Wireless interface and obtain list of access
    # points.
    device = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager",
                                           device_path),
                            "org.freedesktop.NetworkManager.Device.Wireless")
    accesspoints_paths_list = device.GetAccessPoints()

    # Identify our access point. We do this by comparing our desired SSID
    # to the SSID reported by the AP.
    our_ap_path = None
    for ap_path in accesspoints_paths_list:
        ap_props = dbus.Interface(
            bus.get_object("org.freedesktop.NetworkManager", ap_path),
            "org.freedesktop.DBus.Properties")
        ap_ssid = ap_props.Get("org.freedesktop.NetworkManager.AccessPoint",
                               "Ssid")
        # Returned SSID is a list of ASCII values. Let's convert it to a proper
        # string.
        str_ap_ssid = "".join(chr(i) for i in ap_ssid)
        print ap_path, ": SSID =", str_ap_ssid
        if str_ap_ssid == SEEKED_SSID:
            our_ap_path = ap_path
            break

    if not our_ap_path:
        print "AP not found :("
        exit(2)
    print "Our AP: ", our_ap_path

    # At this point we have all the data we need. Let's prepare our connection
    # parameters so that we can tell the NetworkManager what is the passphrase.
    connection_params = {
        "802-11-wireless": {
            "security": "802-11-wireless-security",
        },
        "802-11-wireless-security": {
            "key-mgmt": "wpa-psk",
            "psk": SEEKED_PASSPHRASE
        },
    }

    # Establish the connection.
    settings_path, connection_path = manager.AddAndActivateConnection(
        connection_params, device_path, our_ap_path)
    print "settings_path =", settings_path
    print "connection_path =", connection_path

    # Wait until connection is established. This may take a few seconds.
    NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2
    print """Waiting for connection to reach """ \
          """NM_ACTIVE_CONNECTION_STATE_ACTIVATED state ..."""
    connection_props = dbus.Interface(
        bus.get_object("org.freedesktop.NetworkManager", connection_path),
        "org.freedesktop.DBus.Properties")
    state = 0
    while True:
        # Loop forever until desired state is detected.
        #
        # A timeout should be implemented here, otherwise the program will
        # get stuck if connection fails.
        #
        # IF PASSWORD IS BAD, NETWORK MANAGER WILL DISPLAY A QUERY DIALOG!
        # This is something that should be avoided, but I don't know how, yet.
        #
        # Also, if connection is disconnected at this point, the Get()
        # method will raise an org.freedesktop.DBus.Error.UnknownMethod
        # exception. This should also be anticipated.
        state = connection_props.Get(
            "org.freedesktop.NetworkManager.Connection.Active", "State")
        if state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED:
            break
        time.sleep(0.001)
    print "Connection established!"

    #
    # Connection is established. Do whatever is necessary.
    # ...
    #
    print "Sleeping for 5 seconds ..."
    time.sleep(5)
    print "Disconnecting ..."

    # Clean up: disconnect and delete connection settings. If program crashes
    # before this point is reached then connection settings will be stored
    # forever.
    # Some pre-init cleanup feature should be devised to deal with this problem,
    # but this is an issue for another topic.
    manager.DeactivateConnection(connection_path)
    settings = dbus.Interface(
        bus.get_object("org.freedesktop.NetworkManager", settings_path),
        "org.freedesktop.NetworkManager.Settings.Connection")
    settings.Delete()

    # Disable Wireless (optional step)
    if not was_wifi_enabled:
        manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled",
                          False)
    print "DONE!"
    exit(0)

撰写回答