admin管理员组

文章数量:1570729

 最近遇到的一个需求,需要通过连接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")
        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路由器是否可用……

 

本文标签: jsPythonwifi