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

Posted

技术标签:

【中文标题】在 Linux 上从 Python 连接到受保护的 WiFi【英文标题】:Connecting to a protected WiFi from Python on Linux 【发布时间】:2013-02-06 22:52:12 【问题描述】:

我正在为需要连接到 WiFi AP 的 Ubuntu Linux 创建一个软件。 WiFi 网络不是预定义的,并且可以在软件的单次运行期间更改多次(用户是下令更改的人)。想法是这样的:给定一组 SSID 及其 WPA 或 WEP 密码,软件应该能够随心所欲地在网络之间切换,而无需更改系统中任何位置的任何配置文件。

看起来,最大的问题是将密码传递给连接。到目前为止,我一直在使用以下方法:

Ubuntu 12.10 机器配备 WiFi 加密狗。 Python,运行软件,用于请求连接 康曼 0.79 wpa_supplicant v1.0 d-总线

起初我认为可以通过 d-bus 将密码传递给 connman,但是这个版本的 connman 和 1.11 似乎都没有公开任何方法。然后我发现可以将service_<SSID>.conf 文件转储到/var/lib/connman/ 目录。该文件的内容非常简单,如下所示:

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

创建此文件后,连接到网络需要在适当的服务中简单调用 net.connman.Service.Connect() 方法。问题是 connman 除非重新启动,否则不会解析配置文件。这需要 sudo 权限、额外的时间,并增加了所有“现在可能出错”的事情发生的风险。然后我发现密码可以以某种方式传递给 wpa_supplicant d-bus API,但我什么也没找到。

Google 搜索也让我失望了。好像从来没有人尝试过这样做。

命令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】:

这显示了如何为 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)

【讨论】:

你能告诉我 WEP 的安全命令是什么吗? 抱歉,不需要研究如何使用 WEP 执行此操作,因此我无法在此为您提供帮助。不过,我不认为会有太大的不同。 @ZalewaPL 我知道距离上次回复已经快一年了,但是根据link,您甚至不需要输入安全类型(WEP、WPA2 等),您只需需要提供密码(psk)。 AddAndActivateConnection 的第一个参数的引用:Connection settings and properties; if incomplete missing settings will be automatically completed using the given device and specific object. 所以我从 connection_params 中删除了 securitykey-mgmt 并成功连接。 :) @kv1dr 很高兴知道。很高兴听到这个 SO 条目正在帮助其他人,因为我的计划发生了变化,我没有在任何地方的任何真正的解决方案中使用它。 为未来的读者添加更多信息。可以在here 找到连接设置和属性的完整列表。您主要想查看802-11-wireless-security 设置。

以上是关于在 Linux 上从 Python 连接到受保护的 WiFi的主要内容,如果未能解决你的问题,请参考以下文章

R 可以连接到受 ssl 保护的 MongoDB 实例吗?

无法在 Windows 上从 Python 连接到 MSSQL Server

在 Linux 上从 PHP 连接到 MS Access 数据库

使用 adb shell 连接到受密码保护的 wifi 网络

如何从 Spring JdbcTemplate 连接到受密码保护的 MS Access 数据库?

如何使用 web3 连接到受保护的 infura 项目?