跨平台的pywifi模块支持操作无线网卡,该模块易于使用,同时支持Windows、Linux等多个系统。pywifi模块不是Python的标准模块,需单独安装,同时该模块依赖comtypes模块,最好同时安装comtypes模块,否则调用pywifi的函数时可能会报错。
pip install comtypes
pip install pywifi
pywifi模块中的类不算太多,其中主要用到的类包括PyWiFi、Profile、Interface等,详述如下:
PyWiFi类用于操作无线设备,该类的主要函数interfaces返回可用的无线网卡集合,也即Interface对象集合。
Profile类表示无线接入点(AP),也即无线网卡搜索出的无线连接,一个Profile对象表示一个可以连接或可用的无线连接,Profile类的主要属性如下表所示:
序号 |
属性名 |
说明 |
1 |
ssid |
无线网络名称 |
2 |
auth |
认证算法,包括AUTH_ALG_OPEN、.AUTH_ALG_SHARED两种,默认为AUTH_ALG_OPEN,关于认证算法的介绍详见参考文献5 |
3 |
akm |
授权密钥管理方式,包括AKM_TYPE_NONE、AKM_TYPE_WPA、AKM_TYPE_WPAPSK、AKM_TYPE_WPA2、AKM_TYPE_WPA2PSK、AKM_TYPE_UNKNOWN,默认为AKM_TYPE_NONE,关于授权密钥管理方式详见参考文献6-7 |
4 |
cipher |
密码类型,包括CIPHER_TYPE_NONE、CIPHER_TYPE_WEP、CIPHER_TYPE_TKIP、CIPHER_TYPE_CCMP、CIPHER_TYPE_UNKNOWN,默认为CIPHER_TYPE_NONE |
5 |
key |
无线网络连接密码,如果密码类型不未CIPHER_TYPE_NONE,则应设置本属性值 |
;Interface类用于执行无线网络操作,主要包括以下函数:
序号 |
函数名 |
说明 |
1 |
name |
获取无线网卡名称 |
2 |
scan |
调用无线网卡扫描可用的无线网络(AP) |
3 |
scan_results |
获取scan函数的扫描结果,返回的是Profile对象列表 |
4 |
add_network_profile |
添加特定无线网络(AP)以便后续连接 |
5 |
remove_network_profile |
移除指定的无线网络(AP) |
6 |
remove_all_network_profiles |
移除所有无线网络(AP) |
7 |
network_profiles |
获取保存的所有无线网络(AP) |
8 |
connect |
连接指定的无线网络(AP) |
9 |
disconnect |
断掉当前无线网络连接 |
10 |
status |
获取当前无线网络连接状态 |
最后是照着参考文献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]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