用python或linux终端连接wifi教程
我试图通过python和linux终端连接到wifi,但在这两种情况下它都不能与我合作.
对于python,我使用的是这个库https://wifi.readthedocs.org/en/latest/scanning.html
扫描和保存方案工作正常,但每当我键入这行代码
scheme.activate(),我没有输出
任何想法图书馆有什么问题,如果你以前使用过它?
我还尝试使用CLI连接到WiFi网络.我用Google搜索,发现我应该做这三个陈述
1- iwlist wlan0 scan //扫描wireess网络
2- iwconfig wlan0 essid“Mywirelessnetwork”//与网络关联
3- dhclient wla0 //获得UP
每当我做第2步,然后检查iwconfig wlan0,我发现无线接口没有关联!!
有任何想法吗 ???
我想要做的是建立一个连接到wifi的方法库,最好是通过python函数或库,并在raspberry PI上测试,因为我正在构建一些需要网络连接的应用程序.
解决方法:
这是使用python os模块和Linux iwlist命令搜索wifi设备列表和nmcli命令以便连接到目标设备的一般方法.
在此代码中,run函数查找与您指定的名称(可以是正则表达式模式或服务器名称的唯一部分)匹配的设备的SSID,然后通过调用连接来连接到符合预期条件的所有设备功能.
"""
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()