Python測試網絡連通性示例【基於ping】


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

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM