转自自己的ChinaUnix博客Xiaodylan文章 

今天群里有个童鞋问到我想用python来写一个ping检查多台主机健康状态的一个脚本,还真没写过。然后我就试着写了一下,因为我的python也属于学习阶段所以

还是要借助于好多资料才写成的,当然里面还需要有好多的优化,只是简单的实现了,还请各位多多指出问题,多谢!

新增了一个打开要检查文件列表的功能,输入你要检查的机器的列表文件名.

  1. #!/usr/bin/env python 
  2. #Auther:YooMa 
  3. import os,sys,re 
  4. import subprocess 
  5. def runCheck(source): 
  6.     file_obj = open(source) 
  7.     for host in file_obj.readlines(): 
  8.         host = host.strip('\n'
  9.         p = subprocess.Popen(["ping -c 1 "+ host], 
  10.                             stdin = subprocess.PIPE, 
  11.                             stdout = subprocess.PIPE, 
  12.                             stderr = subprocess.PIPE, 
  13.                             shell = True
  14.         out = p.stdout.read() 
  15.         regex = re.compile("time=\d*", re.IGNORECASE | re.MULTILINE) 
  16.         if len(regex.findall(out)) > 0
  17.             print host+': Host Up!' 
  18.         else
  19.             print host+': Host Down!' 
  20.  
  21. def Usage(): 
  22.     print """ ---Need to enter an absolute path--- 
  23. ---(The current directory except)---""" 
  24.  
  25. while True
  26.     Usage() 
  27.     source = raw_input('Please input your check_host_list_file:'
  28.     if os.path.exists(source): 
  29.         runCheck(source) 
  30.         exit() 
  31.  
  32.     elif source == 'ls'
  33.         print '--------List current directory--------' 
  34.         os.system('ls'
  35.      
  36.     else
  37.         print "Sorry your check_host_list_file not exist!" 

执行结果:

 

  1. 192.168.3.88 :Host up!
  2. 192.168.3.12 :Host up!
  3. 192.168.3.123 :Host down!
  4. 192.168.3.44 :Host up!