python wifi 自动切换

需求

现某司直播,网络不稳定,导致直播异常,原先的解决方式是人工发现异常,然后手动切换网络(4G热点),但是对业务影响较大。
解决方案一是升级公司网络(难度较大),方案二是自动切换网络.
现在写一个脚本自动检测网络,当网络异常时,自动切换到可用的wifi。

实现

操作系统:windows 10
连接命令:netsh wlan connect name=”%s”
查看当前wifi:netsh wlan show interfaces
查看所有wifi:netsh wlan show profile
语言: python2.7
检查网络:ping www.baidu.com -n 2 -w 1000
总体逻辑是,循环ping一个常用的IP地址检测网络,发现异常后,netsh连接到到另一个网络。
“人生苦短,我用python”
实现效果较好,3-5秒内能自动切换网络
python wifi 自动切换_第1张图片
python wifi 自动切换_第2张图片

注意

  • 切换网络的时候,要再次检查当前网络是什么(中间可能手动更换的链接)
  • 切换网络后,需要sleep 15s,等待系统生效,不然还是连不上网,导致循环切换网络
  • ping检查不要太频繁,每次检查后sleep 1s,降低cpu利用率
  • 一次ping要两次,避免网络波动
  • 调用接口,多余的日志要抛弃掉,防止日志堆积

其他应用

网上打游戏的时候,小区网络经常波动,坑队友,使用本脚本后可自动切换到手机热点,继续超神

代码

#just for windows
#auto switch to available wifi
#author: Nickwong
import os
import time
import datetime
import subprocess
import Tkinter
import tkMessageBox

def check_ping(ip, count = 1, timeout = 1000):
    cmd = 'ping -n %d -w %d %s > NUL' % (count,timeout,ip)
    response = os.system(cmd)
    # and then check the response...
    # 0 for ok, no 0 for failed
    return "ok" if response == 0 else "failed"

''' see wifi name list: netsh wlan show profile more netsh & wifi command https://www.hanselman.com/blog/HowToConnectToAWirelessWIFINetworkFromTheCommandLineInWindows7.aspx '''
def connect_wifi(wifiProfile):
    cmd = 'netsh wlan connect name="%s"' % wifiProfile;
    return os.system(cmd)

def get_current_wifi(wifiList):
    cmd = 'netsh wlan show interfaces'
    p = subprocess.Popen(cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True
        )
    ret = p.stdout.read()
    for index in range(len(wifiList)):
        if ret.find(wifiList[index]) >=0 :
            return index
    return 0

def show_messagebox():
    tkMessageBox.showwarning("Title", 'Network is unstable')

def auto_switch_wifi(ipTest, wifiList):
    lastMinute = 0
    while(True):
        #sleep to save power
        time.sleep(1)
        now = datetime.datetime.now()
        #ping twice to ignore network fluctuation
        pingStatus = check_ping(ipTest,2)
        if now.minute != lastMinute:
            lastMinute = now.minute
            print now.strftime("%Y-%m-%d %H:%M:%S"),'',pingStatus
        if pingStatus != 'ok':
            index = get_current_wifi(wifiList)
            index = 1 - index
            print '---auto switch wifi from "%s" to "%s", waiting for 15s' % (wifiList[1-index],wifiList[index])
            connect_wifi(wifiList[index])
            show_messagebox()
            #switch need a delay, good coffee need time to cook
            time.sleep(15)

def test():
     while(True):
        print wifiList[get_current_wifi(wifiList)]

if __name__ == "__main__":
    #baidu.com ip
    ipTest = '61.135.169.121'
    #wifi must match blow name
    wifiList = ['Mi Note 3','wifi-58']
    print 'test ip:',ipTest
    print 'wifiList:', wifiList
    auto_switch_wifi(ipTest,wifiList)

你可能感兴趣的:(技术应用)