Automatic switch of python wifi

Posted by mwalsh on Sat, 04 Apr 2020 18:05:14 +0200

demand

At present, the network of a company's live broadcast is unstable, resulting in the live broadcast exception. The original solution is to manually find the exception, and then manually switch the network (4G hotspot), but it has a great impact on the business.
The first solution is to upgrade the company's network (difficult), and the second is to switch the network automatically
Now write a script to automatically detect the network. When the network is abnormal, it will automatically switch to the available wifi.

Realization

Operating system: windows 10
Connect command: netsh wlan connect name = "% s"
View the current wifi: netsh wlan show interfaces
Check the network: Ping w w w.baidu.com - N 2 - W 1000
The overall logic is to loop ping a common IP address detection network. When an exception is found, netsh connects to another network.
"Life is short, I use python"
The implementation effect is good, and the network can be switched automatically within 3-5 seconds

Be careful

  • When switching the network, check again what the current network is (links may be manually replaced in the middle)
  • After switching the network, you need to sleep for 15s and wait for the system to take effect. Otherwise, you still can't connect to the Internet, resulting in cyclic network switching
  • ping check should not be too frequent. Sleep 1 s after each check to reduce cpu utilization
  • ping twice at a time to avoid network fluctuations
  • Call the interface, and discard the redundant logs to prevent log accumulation

Code

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

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 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 > 0 :
            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])
            #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)

Topics: network Windows Python shell