3-python库之-pywifi无线网卡控制

在做路由器测试的时候,需要控制无线网卡,让其自动连接断开等操作,pywifi可以实现该功能,当时现在只有window和Linux平台的,mac平台没办法用。

pip install pywifi

pip install comtypes

1.获取无线网卡接口

有时候一台电脑上有多张网卡,这时候我们需要选择自己需要的网卡进行SSID链接。

使用pywifi.PyWiFi接口创建实例的时候,就会返回我们一共检测到几张网卡,然后通过wifi.interfaces.name()可以获取到每个网卡的名字,我们再根据自己的需求,选择对应的网卡。

def get_wifi_interfaces():
    wifi = pywifi.PyWiFi()  # 创建一个无限对象
    num = len(wifi.interfaces())
    if num <= 0:
        logging.info("未找到无线网卡接口!\n")
        exit()
    if num == 1:
        wifi_iface = wifi.interfaces()[0]  # 取一个无限网卡
        logging.info(u"无线网卡接口: %s\n" % (wifi_iface.name()))
        return wifi_iface
    else:
        logging.info('%-4s   %s\n' % (u'序号', u'网卡接口名称'))
        for i, w in enumerate(wifi.interfaces()):
            logging.info('%-4s   %s' % (i, w.name()))
        while True:
            iface_no = input('请选择网卡接口序号:'.encode('utf-8').decode('gbk'))
            no = int(iface_no)
            if no >= 0 and no < num:
                return wifi.interfaces()[no]

2.扫描周围存在的SSID

我们在选择网卡之后就要链接热点的SSID,这时候我们一般 需要先扫描一遍周围的环境,确认存在我们要链接的这个SSID。

# 扫描周围wifi
def scan_wifi(self):
    self.scan()   # 扫描
    time.sleep(3)
    wifi_info = self.scan_results()
    wifi_list = []
    for i in wifi_info:
        if i.signal > -90:  # 信号强度<-90的wifi几乎连不上
            wifi_list.append((i.ssid, i.signal, i.freq, i.bssid, i.akm))  # 添加到wifi列表
            logging.info("ssid: %s, 信号: %s, freq: %s, mac: %s, 加密方式: %s",
                         i.ssid.encode('raw_unicode_escape', 'strict').decode('utf-8'), i.signal, i.freq, i.bssid, i.akm)

    return sorted(wifi_list, key=lambda x: x[1], reverse=True)  # 按信号强度由高到低排序

使用scan()函数扫描,等待几秒后使用scan_results()获取扫描结果,再将设备信息保存起来,供我们匹配用。

3.连接WIFI SSID

找到对应的WIFI SSID后,就可以用SSID对应的密码,加密方式进行连接(加密方式,我们在上面的扫描结果里面可以获取到)

连接后可以使用status()接口判断是否连接成功。

# 连接wifi
def connect_wifi(self):
    profile_info = pywifi.profile.Profile()  # 配置文件
    profile_info.ssid = "TEST_24G"  # wifi名称
    profile_info.key = "12345678"   # wifi密码
    profile_info.auth = pywifi.const.AUTH_ALG_OPEN
    profile_info.akm.append(pywifi.const.AKM_TYPE_WPA2PSK)  # 加密类型
    profile_info.cipher = pywifi.const.CIPHER_TYPE_CCMP     # 加密单元

    self.remove_all_network_profiles()  # 删除其他配置文件
    logging.info("删除其他配置文件")
    time.sleep(2)  # 删除其他配置文件
    tmp_profile = self.add_network_profile(profile_info)  # 加载配置文件

    self.connect(tmp_profile)  # 连接
    time.sleep(10)  # 尝试10秒能否成功连接

    logging.info(self.status())
    if self.status() == pywifi.const.IFACE_CONNECTED:
        logging.info("成功连接")
        return True
    else:
        logging.info("失败")
        self.disconnect()  # 断开连接
        time.sleep(2)
        return False

4.断开连接

断开连接比较简单,如下:

# 断开无线网卡已连接状态
def disconnect_wifi(self):
    self.disconnect()
    time.sleep(2)
    if self.status() in [pywifi.const.IFACE_DISCONNECTED, pywifi.const.IFACE_INACTIVE]:
        logging.info(u'无线网卡:%s 已断开。' % self.name())
        return True
    else:
        logging.info(u'无线网卡:%s 未断开。' % self.name())
        return False

5.综合实例

使用上面的接口就可以写出大概的连接逻辑:

def start_connect_wifi(info):
    wifi = get_wifi_interfaces()
    if check_interfaces(wifi):
        disconnect_wifi(wifi)

    scan_i = 0
    scan_result = False
    while scan_i < 5:
        wifi_list = scan_wifi(wifi)
        scan_i += 1
        for wifi_i in wifi_list:
            if wifi_i[0] == info["ssid"]:
                logging.info("find ssid:%s", info["ssid"])
                scan_result = True
                scan_i = 5
                break

    if not scan_result:
        logging.info("find ssid:%s fail", info["ssid"])
        return False

    conn_result = connect_wifi(wifi)
    time.sleep(2)
    if check_interfaces(wifi):
        disconnect_wifi(wifi)

    return conn_result

https://github.com/awkman/pywifi

WLAN API:
https://www.cnblogs.com/gaidao/p/4086850.html

https://blog.csdn.net/qq_38882327/article/details/89349399

发布了106 篇原创文章 · 获赞 76 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/Creator_Ly/article/details/104410927