pywifi

用python操作wifi的代码,实现了扫描,连接的基本功能。具体怎么用,你懂的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pywifi,time
from pywifi import const
def wifi_connect_status():
wifi=pywifi.PyWiFi()
iface=wifi.interfaces()[0]
if iface.status() in [const.IFACE_CONNECTED,const.IFACE_INACTIVE]:
print('wifi已连接')
else:
print('wifi未连接')
return 0
def scan_wifi():
wifi=pywifi.PyWiFi()
iface=wifi.interfaces()[0]
iface.scan()
time.sleep(1)
basewifi=iface.scan_results()
for i in basewifi:
print('wifi ssid:{}'.format(i.ssid))
print('wifi mac:{}'.format(i.bssid))
return basewifi
def connect_wifi(ssid,pw):
wifi=pywifi.PyWiFi()
ifaces=wifi.interfaces()[0]
print(ifaces.name())
ifaces.disconnect()
time.sleep(3)

profile=pywifi.Profile()
profile.ssid=ssid
profile.auth=const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher=const.CIPHER_TYPE_CCMP
profile.key=pw

ifaces.remove_all_network_profiles()
tmp_profile=ifaces.add_network_profile(profile)

ifaces.connect(tmp_profile)
time.sleep(10)
isok=True
if ifaces.status()==const.IFACE_CONNECTED:
print('connected')
else:
print('faild')
time.sleep(1)
return isok

if __name__=='__main__':
wifi_connect_status()
time.sleep(5)
scan_wifi()