简体   繁体   English

连接 WiFi python 的最简单方法

[英]Simplest way to connect WiFi python

I would like to connect to my wifi network using python.我想使用 python 连接到我的 wifi 网络。 I know the SSID and the key for the network, and it's encrypted in WPA2 security.我知道网络的 SSID 和密钥,并且它在 WPA2 安全性中加密。 I have seen some libraries like wireless and pywifi but the first didn't work and the second was too complicated.我见过一些图书馆,比如无线和 pywifi,但第一个没有用,第二个太复杂了。 What is the simpelest way to connect to wifi?连接wifi最简单的方法是什么? what is the best library/way?什么是最好的图书馆/方式?

My failed code using wireless library (I've installed it via pip, of course):我使用无线库的失败代码(当然,我是通过 pip 安装的):

from wireless import Wireless

wire = Wireless()
wire.connect(ssid='myhome',password='password')

interpreter output:解释器 output:

Traceback (most recent call last):
File "C:/Users/Aviv/PycharmProjects/Networks/WiFi/1/1.py", line 4, in 
<module>
wire = Wireless()
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 23, in 
__init__
self._driver_name = self._detectDriver()
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 50, in 
_detectDriver
compare = self.vercmp(ver, "0.9.9.0")
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 71, in vercmp
return cmp(normalize(actual), normalize(test))
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 70, in 
normalize
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]
ValueError: invalid literal for int() with base 10: 'file'

Easy way to connect Wifi without any modules:无需任何模块即可轻松连接 Wifi:

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):
        cmd = "nmcli d wifi connect {} password {} iface {}".format(name,
            self.password,
            self.interface_name)
        try:
            if os.system(cmd) != 0: # This will run the command and check connection
                raise Exception()
        except:
            raise # Not Connected
        else:
            return True # Connected

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()

I hope you are using a windows machine.我希望你使用的是 Windows 机器。 Then you should install winwifi module.然后你应该安装winwifi模块。 Before installing the winwifi module, it is better to install plumbum module .在安装winwifi模块之前,最好先安装plumbum模块 Try it install in python 32 bit version.尝试将其安装在 python 32 位版本中。

Click this to install plumbum module: https://pypi.org/project/plumbum/点击这里安装plumbum模块: https : //pypi.org/project/plumbum/

Then install winwifi : https://pypi.org/project/winwifi/然后安装 winwifi: https ://pypi.org/project/winwifi/

Now you could try connecting a known wifi using the following code:现在您可以尝试使用以下代码连接已知的 wifi:

import winwifi
winwifi.WinWiFi.connect('ssid_of_the_router')

This module has many more commands like:这个模块有更多的命令,比如:

winwifi.WinWiFi.disconnect() winwifi.WinWiFi.disconnect()

winwifi.WinWiFi.addprofile('ssid_of_new_router'), etc. winwifi.WinWiFi.addprofile('ssid_of_new_router') 等

You can check this by exploring my github repository: https://github.com/ashiq-firoz/winwifi_Guide您可以通过浏览我的 github 存储库来检查这一点: https : //github.com/ashiq-firoz/winwifi_Guide

If you are using Ubuntu/linux, you can use the natively available network manager cli package (nmcli):如果您使用的是 Ubuntu/linux,则可以使用本机可用的网络管理器 cli package (nmcli):

import subprocess

def what_wifi():
    process = subprocess.run(['nmcli', '-t', '-f', 'ACTIVE,SSID', 'dev', 'wifi'], stdout=subprocess.PIPE)
    if process.returncode == 0:
        return process.stdout.decode('utf-8').strip().split(':')[1]
    else:
        return ''

def is_connected_to(ssid: str):
    return what_wifi() == ssid

def scan_wifi():
    process = subprocess.run(['nmcli', '-t', '-f', 'SSID,SECURITY,SIGNAL', 'dev', 'wifi'], stdout=subprocess.PIPE)
    if process.returncode == 0:
        return process.stdout.decode('utf-8').strip().split('\n')
    else:
        return []
        
def is_wifi_available(ssid: str):
    return ssid in [x.split(':')[0] for x in scan_wifi()]

def connect_to(ssid: str, password: str):
    if not is_wifi_available(ssid):
        return False
    subprocess.call(['nmcli', 'd', 'wifi', 'connect', ssid, 'password', password])
    return is_connected_to(ssid)

def connect_to_saved(ssid: str):
    if not is_wifi_available(ssid):
        return False
    subprocess.call(['nmcli', 'c', 'up', ssid])
    return is_connected_to(ssid)

Connect to a saved network:连接到已保存的网络:

connect_to_saved('my_wifi')

Otherwise, connect to a network with ssid and password:否则,使用 ssid 和密码连接到网络:

connect_to('my_wifi', 'my_password')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM