code
import os import time PING_RESULT = 0 NETWORK_RESULT = 0 def DisableNetwork(): ''' disable network card ''' result = os.system(u"netsh interface set interface 以太网 disable") if result == 1: print("disable network card failed") else: print("disable network card successfully") def ping(): ''' ping 主备网络 ''' result = os.system(u"ping 180.97.33.108") #result = os.system(u"ping www.baidu.com -n 3") if result == 0: print("A网正常") else: print("网络故障") return result if __name__ == '__main__': while True: PING_RESULT = ping() if PING_RESULT == 0: time.sleep(20) else: DisableNetwork() time.sleep(10)
根据平台ping
import os
import platform
import logging
log = logging.getLogger(__name__)
def ping(addr): if(platform.system()=='Darwin'): result = os.system(u"ping {} -c 3".format(addr)) elif(platform.system()=='Windows'): result = os.system(u"ping {} -n 3".format(addr)) elif(platform.system()=='Linux'): result = os.system(u"ping {} -c 3".format(addr)) else: print("unknown platform!") if result == 0: logging.info("{}:网络正常".format(addr)) else: logging.info("{}:网络故障".format(addr)) return result
PING_RESULT = ping("www.baidu.com")
assert PING_RESULT == 0