• 学习Python中pywifi模块的基本用法


      跨平台的pywifi模块支持操作无线网卡,该模块易于使用,同时支持Windows、Linux等多个系统。pywifi模块不是Python的标准模块,需单独安装,同时该模块依赖comtypes模块,最好同时安装comtypes模块,否则调用pywifi的函数时可能会报错。

    pip install comtypes
    pip install pywifi
    
    • 1
    • 2

      pywifi模块中的类不算太多,其中主要用到的类包括PyWiFi、Profile、Interface等,详述如下:
      PyWiFi类用于操作无线设备,该类的主要函数interfaces返回可用的无线网卡集合,也即Interface对象集合。
      Profile类表示无线接入点(AP),也即无线网卡搜索出的无线连接,一个Profile对象表示一个可以连接或可用的无线连接,Profile类的主要属性如下表所示:

    序号属性名说明
    1ssid无线网络名称
    2auth认证算法,包括AUTH_ALG_OPEN、.AUTH_ALG_SHARED两种,默认为AUTH_ALG_OPEN,关于认证算法的介绍详见参考文献5
    3akm授权密钥管理方式,包括AKM_TYPE_NONE、AKM_TYPE_WPA、AKM_TYPE_WPAPSK、AKM_TYPE_WPA2、AKM_TYPE_WPA2PSK、AKM_TYPE_UNKNOWN,默认为AKM_TYPE_NONE,关于授权密钥管理方式详见参考文献6-7
    4cipher密码类型,包括CIPHER_TYPE_NONE、CIPHER_TYPE_WEP、CIPHER_TYPE_TKIP、CIPHER_TYPE_CCMP、CIPHER_TYPE_UNKNOWN,默认为CIPHER_TYPE_NONE
    5key无线网络连接密码,如果密码类型不未CIPHER_TYPE_NONE,则应设置本属性值

      ;Interface类用于执行无线网络操作,主要包括以下函数:

    序号函数名说明
    1name获取无线网卡名称
    2scan调用无线网卡扫描可用的无线网络(AP)
    3scan_results获取scan函数的扫描结果,返回的是Profile对象列表
    4add_network_profile添加特定无线网络(AP)以便后续连接
    5remove_network_profile移除指定的无线网络(AP)
    6remove_all_network_profiles移除所有无线网络(AP)
    7network_profiles获取保存的所有无线网络(AP)
    8connect连接指定的无线网络(AP)
    9disconnect断掉当前无线网络连接
    10status获取当前无线网络连接状态

      最后是照着参考文献3编写的测试程序(测试前请确保已记住当前计算机连接的wifi密码)

    import pywifi
    
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]
    
    print('interface name: ',iface.name())
    print('interface status: ',iface.status())
    
    iface.disconnect()
    print('interface status: ',iface.status())
    
    profile = pywifi.Profile()
    profile.ssid = "XXXXXXX"
    profile.auth = pywifi.const.AUTH_ALG_OPEN 
    profile.akm.append(pywifi.const.AKM_TYPE_WPA2PSK)
    profile.cipher = pywifi.const.CIPHER_TYPE_CCMP
    profile.key = 'XXXXXXX'
    iface.remove_all_network_profiles()
    tep_profile = iface.add_network_profile(profile)
    iface.connect(tep_profile)
    
    sleep(5)
    print('interface status: ',iface.status())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    参考文献
    [1]https://github.com/awkman/pywifi
    [2]https://github.com/awkman/pywifi/blob/master/DOC.md
    [3]https://blog.csdn.net/Feng_liangmu/article/details/122911002
    [4]https://docs.python.org/zh-cn/3/index.html
    [5]https://www.likecs.com/show-655827.html
    [6]https://www.likecs.com/show-655827.html
    [7]https://code84.com/739564.html

  • 相关阅读:
    [C++] C++标准库中的string类的使用(上)、
    C++ functional库中的仿函数
    TPM分析笔记(十)TPM 组织架构(TPM hierarchy)
    C++中的函数重载:多功能而强大的特性
    LeetCode每日一题(2348. Number of Zero-Filled Subarrays)
    代码首次提交到gitee上报错问题解决
    华为FreeBuds Pro 2戴久了耳朵会痛,缓解小tips~
    成都理工大学_Python程序设计_第6章
    【C++】深拷贝和浅拷贝 ③ ( 浅拷贝内存分析 )
    【开发教程5】开源蓝牙心率防水运动手环-电池电量检测
  • 原文地址:https://blog.csdn.net/gc_2299/article/details/128058252