最近遇到的一個需求,需要通過連接wifi判斷是否路由器可用。
python服務端:
import subprocess as sp
import logging
import subprocess as sp
import time
import pywifi
from flask import Flask, make_response, jsonify
from flask_cors import CORS
from pywifi import const
global data
app = Flask(__name__)
logger = logging.getLogger(__name__)
logger.error("time:{}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
try:
# w:覆蓋式寫入
# a:追加式寫入
with open('test.txt', 'w', encoding='utf-8', errors='ignore') as f:
f.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
except:
pass
@app.route("/")
def index():
# 路由器
bool = connect_wifi_password("wwbnqdfg_5G", "zzfXXXXXXX")
data=''
if (bool == True):
status, result = sp.getstatusoutput("ping " + "www.baidu.com")
if status == 1:
data = "false"
else:
data = "true"
else:
data = "false"
# 連接回原wifi了
connect_wifi_password("wwbnqdfg_5G", "zzfXXXXXXX")
result_text = {"statusCode": 200, "message": data}
response = make_response(jsonify(result_text))
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST'
response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
return response
def connect_wifi_password(wifiName, password):
wifi = pywifi.PyWiFi() # 創建一個wifi對象
ifaces = wifi.interfaces()[0] # 取第一個無限網卡
ifaces.disconnect() # 斷開網卡連接
time.sleep(3) # 緩衝3秒
profile = pywifi.Profile() # 配置文件
profile.ssid = wifiName # wifi名稱
profile.auth = const.AUTH_ALG_OPEN # 需要密碼
profile.akm.append(const.AKM_TYPE_WPA2PSK) # 加密類型
profile.cipher = const.CIPHER_TYPE_CCMP # 加密單元
profile.key = password # wifi密碼
ifaces.remove_all_network_profiles() # 刪除其他配置文件
tmp_profile = ifaces.add_network_profile(profile) # 加載配置文件
ifaces.connect(tmp_profile) # 連接
time.sleep(5) # 嘗試10秒能否成功連接
isok = True
if ifaces.status() == const.IFACE_CONNECTED:
print("成功連接")
else:
print("失敗")
isok = False
time.sleep(1)
return isok
if __name__ == "__main__":
app.run(host='127.0.0.1', threaded=True, debug=True)
CORS(app)
Js調用方式:
$.ajax({
url: 'http://localhost:5000/',
type: 'get',
success: function(data) {
if(data["message"] == "true") {
…… //wifi可用
}
},
error: function(error) {
……
}
});
這裏可以用bat文件啓動這個py腳本,這樣就能通過接口的方式去判斷當前wifi路由器是否可用……