使用python或linux终端连接wifi



我正试图通过python和linux终端连接到wifi,但在这两种情况下都无法使用。

对于python,我使用这个库https://wifi.readthedocs.org/en/latest/scanning.html扫描并保存该方案运行良好,但每当我键入这行代码时scheme.activate(),我没有得到输出

你知道图书馆出了什么问题吗?你以前是否使用过它??

我还尝试使用CLI连接到WiFi网络。我在谷歌上搜索了一下,发现我应该做这三个陈述1-iwlist wlan0扫描//扫描无线网络2-iwconfig wlan0 sessiond"Mywirelessnetwork"//与网络关联3-dhclient wla0//获取UP

每当我执行步骤2,然后检查iwconfig wlan0时,我发现无线接口没有关联!!

有什么想法吗???

我想做的是有一个连接wifi的方法库,最好是通过python功能或库,并在树莓PI上进行测试,因为我正在构建一些需要网络连接的应用程序。

以下是一种使用pythonos模块和Linuxiwlist命令搜索wifi设备列表和nmcli命令连接到预期设备的通用方法。

在该代码中,run函数查找与指定名称匹配的设备的SSID(可以是正则表达式模式或服务器名称的唯一部分),然后通过调用connection函数连接到与预期条件匹配的所有设备。

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

class WifiFinder:
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  
WF = WifiFinder(server_name=server_name,
password=password,
interface=interface_name)
WF.run()

首先尝试查看以下链接:http://packages.ubuntu.com/raring/python-wicdhttps://wifi.readthedocs.org/en/latest/

如果你想通过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_passwordn')
while handle.poll() == None:
print handle.stdout.readline().strip()  # print the result

但请确保您在Linux中以超级用户身份运行,但在Windows中没有问题。

最新更新