使用python或linux终端连接wifi

时间:2021-02-10 17:31:15

I am trying to connect to wifi through python and linux terminal but in both cases it is not working with me.

我正在尝试通过python和linux终端连接到wifi,但在这两种情况下都不能正常工作。

For python, I am using this library https://wifi.readthedocs.org/en/latest/scanning.html scanning and saving the scheme is working fine but whenever I type this line of code scheme.activate() and I get no output

对于python,我正在使用这个库https://wifi.readthedocs.org/en/latest/scannning .html扫描和保存方案很好,但是每当我输入这行代码scheme.activate()时,我就得不到任何输出

Any ideas what is wrong with the library and if you have used it before or not??

你知道图书馆有什么问题吗?你以前用过吗?

I tried also to connect to WiFi networks using the CLI. I Googled and found that I should do these three statements 1- iwlist wlan0 scan // to scan the wireess networks 2- iwconfig wlan0 essid "Mywirelessnetwork" // to associate with the network 3- dhclient wla0 // To get an UP

我还尝试使用CLI连接到WiFi网络。我在谷歌上搜索发现,我应该做以下三个语句:1- iwlist wlan0 scan //扫描无线网络2- iwconfig wlan0 essid“Mywirelessnetwork”// /与网络3- dhclient wla0 // /关联,以获得成功

Whenever I do step 2 and then check iwconfig wlan0 I found that the wireless interface is not associated !!

无论何时我做步骤2,然后检查iwconfig wlan0,我发现无线接口没有关联!!

Any ideas ???

任何想法? ? ?

What I am trying to do is to have a library of a way to connect to the wifi preferably through a python function or a library and tested on raspberry PI because I am building some applications that require network connection.

我想做的是建立一个库,通过python函数或库连接到wifi,并在raspberry PI上进行测试,因为我正在构建一些需要网络连接的应用。

2 个解决方案

#1


1  

Here is a general approach using python os module and Linux iwlist command for searching through the list of wifi devices and nmcli command in order to connect to a the intended device.

下面是一种使用python os模块和Linux iwlist命令搜索wifi设备列表和nmcli命令的通用方法,以便连接到预期的设备。

In this code the run function finds the SSID of devices that match with your specified name (which can be a regex pattern or a unique part of the server name) then connects to all the devices that match with your expected criteria, by calling the connection function.

在这段代码中,run函数查找与您指定的名称(可以是regex模式或服务器名称的唯一部分)匹配的设备的SSID,然后通过调用connection函数连接到与您期望的标准匹配的所有设备。

"""
Search for a specific wifi ssid and connect to it.
written by kasramvd.
"""
import os


class Finder:
    def __init__(self, *args, **kwargs):
        self.server_name = kwargs['server_name']
        self.password = kwargs['password']
        self.interface_name = kwargs['interface']
        self.main_dict = {}

    def run(self):
        command = """sudo iwlist wlp2s0 scan | grep -ioE 'ssid:"(.*{}.*)'"""
        result = os.popen(command.format(self.server_name))
        result = list(result)

        if "Device or resource busy" in result:
                return None
        else:
            ssid_list = [item.lstrip('SSID:').strip('"\n') for item in result]
            print("Successfully get ssids {}".format(str(ssid_list)))

        for name in ssid_list:
            try:
                result = self.connection(name)
            except Exception as exp:
                print("Couldn't connect to name : {}. {}".format(name, exp))
            else:
                if result:
                    print("Successfully connected to {}".format(name))

    def connection(self, name):
        try:
            os.system("nmcli d wifi connect {} password {} iface {}".format(name,
       self.password,
       self.interface_name))
        except:
            raise
        else:
            return True

if __name__ == "__main__":
    # Server_name is a case insensitive string, and/or regex pattern which demonstrates
    # the name of targeted WIFI device or a unique part of it.
    server_name = "example_name"
    password = "your_password"
    interface_name = "your_interface_name" # i. e wlp2s0  
    F = Finder(server_name=server_name,
               password=password,
               interface=interface_name)
    F.run()

#2


1  

At first try to look at these links: http://packages.ubuntu.com/raring/python-wicd https://wifi.readthedocs.org/en/latest/

首先看看这些链接:http://packages.ubuntu.com/raring/python-wicd https://wifi.readthedocs.org/en/latest/

And if you want to use bash commands via python try this code:

如果您想通过python使用bash命令,请尝试以下代码:

from subprocess import Popen, STDOUT, PIPE
from time import sleep

handle = Popen('netsh wlan connect wifi_name', stdout=PIPE, stdin=PIPE, shell=True,  stderr=STDOUT)

sleep(10)

handle.stdin.write(b'wifi_password\n')
while handle.poll() == None:
    print handle.stdout.readline().strip()  # print the result

But make sure you are running as a super user in Linux but there is no problem in Windows.

但是要确保您在Linux中作为超级用户运行,但是在Windows中没有问题。

#1


1  

Here is a general approach using python os module and Linux iwlist command for searching through the list of wifi devices and nmcli command in order to connect to a the intended device.

下面是一种使用python os模块和Linux iwlist命令搜索wifi设备列表和nmcli命令的通用方法,以便连接到预期的设备。

In this code the run function finds the SSID of devices that match with your specified name (which can be a regex pattern or a unique part of the server name) then connects to all the devices that match with your expected criteria, by calling the connection function.

在这段代码中,run函数查找与您指定的名称(可以是regex模式或服务器名称的唯一部分)匹配的设备的SSID,然后通过调用connection函数连接到与您期望的标准匹配的所有设备。

"""
Search for a specific wifi ssid and connect to it.
written by kasramvd.
"""
import os


class Finder:
    def __init__(self, *args, **kwargs):
        self.server_name = kwargs['server_name']
        self.password = kwargs['password']
        self.interface_name = kwargs['interface']
        self.main_dict = {}

    def run(self):
        command = """sudo iwlist wlp2s0 scan | grep -ioE 'ssid:"(.*{}.*)'"""
        result = os.popen(command.format(self.server_name))
        result = list(result)

        if "Device or resource busy" in result:
                return None
        else:
            ssid_list = [item.lstrip('SSID:').strip('"\n') for item in result]
            print("Successfully get ssids {}".format(str(ssid_list)))

        for name in ssid_list:
            try:
                result = self.connection(name)
            except Exception as exp:
                print("Couldn't connect to name : {}. {}".format(name, exp))
            else:
                if result:
                    print("Successfully connected to {}".format(name))

    def connection(self, name):
        try:
            os.system("nmcli d wifi connect {} password {} iface {}".format(name,
       self.password,
       self.interface_name))
        except:
            raise
        else:
            return True

if __name__ == "__main__":
    # Server_name is a case insensitive string, and/or regex pattern which demonstrates
    # the name of targeted WIFI device or a unique part of it.
    server_name = "example_name"
    password = "your_password"
    interface_name = "your_interface_name" # i. e wlp2s0  
    F = Finder(server_name=server_name,
               password=password,
               interface=interface_name)
    F.run()

#2


1  

At first try to look at these links: http://packages.ubuntu.com/raring/python-wicd https://wifi.readthedocs.org/en/latest/

首先看看这些链接:http://packages.ubuntu.com/raring/python-wicd https://wifi.readthedocs.org/en/latest/

And if you want to use bash commands via python try this code:

如果您想通过python使用bash命令,请尝试以下代码:

from subprocess import Popen, STDOUT, PIPE
from time import sleep

handle = Popen('netsh wlan connect wifi_name', stdout=PIPE, stdin=PIPE, shell=True,  stderr=STDOUT)

sleep(10)

handle.stdin.write(b'wifi_password\n')
while handle.poll() == None:
    print handle.stdout.readline().strip()  # print the result

But make sure you are running as a super user in Linux but there is no problem in Windows.

但是要确保您在Linux中作为超级用户运行,但是在Windows中没有问题。