概念是將無線網路參數加入wpa_supplicant.conf來進行連線,若不用語法控制,其實直接將網路資訊設定在wpa_supplicant.conf中也可以。
位置:
sudo nano/etc/wpa_supplicant/wpa_supplicant.conf
安裝Pywifi
pip install pywifi
連線範例程式:
import pywifi
import sys
import time
from pywifi import const
wifi=pywifi.PyWiFi()
ifaces= wifi.interfaces()[0]
profiles = ifaces.network_profiles()
ifaces.disconnect()
profile=pywifi.Profile()
profile.ssid="[無線網路名稱]"
profile.key="[無線網路密碼]"
profile.auth=const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher=const.CIPHER_TYPE_CCMP
#移除舊的設定參數
ifaces.remove_all_network_profiles()
#加入新的的設定參數
new_profile=ifaces.add_network_profile(profile)
time.sleep(2)
print('add profiles.ssid:'+str(profiles[0].ssid))
print('------')
#進行連線
ifaces.connect(new_profile)
#等候連線
time.sleep(10)
測試經驗是 pywifi的狀態檢查通能不太可靠,等候連線的時間可能10秒到1分鐘以上。
相關profile參數補充如下:
# Define interface status.
IFACE_DISCONNECTED = 0
IFACE_SCANNING = 1
IFACE_INACTIVE = 2
IFACE_CONNECTING = 3
IFACE_CONNECTED = 4
# Define auth algorithms.
AUTH_ALG_OPEN = 0
AUTH_ALG_SHARED = 1
# Define auth key mgmt types.
AKM_TYPE_NONE = 0
AKM_TYPE_WPA = 1
AKM_TYPE_WPAPSK = 2
AKM_TYPE_WPA2 = 3
AKM_TYPE_WPA2PSK = 4
AKM_TYPE_UNKNOWN = 5
# Define ciphers.
CIPHER_TYPE_NONE = 0
CIPHER_TYPE_WEP = 1
CIPHER_TYPE_TKIP = 2
CIPHER_TYPE_CCMP = 3
CIPHER_TYPE_UNKNOWN = 4
KEY_TYPE_NETWORKKEY = 0
KEY_TYPE_PASSPHRASE = 1
搜尋無線網路範例程式:
wifi=pywifi.PyWiFi()#建立一個wifi物件
ifaces= wifi.interfaces()[0]#取第一個無限網絡卡
print(ifaces.name())#輸出無線網絡卡名稱
ifaces.scan()
scanResult = ifaces.scan_results()
time.sleep(10)
if scanResult is not None:
for profile in scanResult:
ssid = profile.ssid
print(profile)
print('SSID:'+profile.ssid)
print('AUTH:'+str(profile.auth))
print('cipher:'+str(profile.cipher))
print('AKM:'+str(profile.akm))
else:
print ('未找到wifi')
沒有留言:
張貼留言