Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1925639
  • 博文数量: 498
  • 博客积分: 2078
  • 博客等级: 大尉
  • 技术积分: 1645
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-18 22:43
个人简介

安大

文章分类

全部博文(498)

文章存档

2017年(1)

2016年(2)

2015年(21)

2014年(90)

2013年(101)

2012年(267)

2011年(16)

分类: Python/Ruby

2013-04-11 12:06:35

今天群里有个童鞋问到我想用python来写一个ping检查多台主机健康状态的一个脚本,还真没写过。然后我就试着写了一下,因为我的python也属于学习阶段所以
还是要借助于好多资料才写成的,当然里面还需要有好多的优化,只是简单的实现了,还请各位多多指出问题,多谢!

新增了一个打开要检查文件列表的功能,输入你要检查的机器的列表文件名.
代码:
  1. #!/usr/bin/env python
  2. #Auther:XaoSa
  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. def Usage():
  21.     print """ ---Need to enter an absolute path---
  22. ---(The current directory except)---"""

  23. while True:
  24.     Usage()
  25.     source = raw_input('Please input your check_host_list_file:')
  26.     if os.path.exists(source):
  27.         runCheck(source)
  28.         exit()

  29.     elif source == 'ls':
  30.         print '--------List current directory--------'
  31.         os.system('ls')
  32.     
  33.     else:
  34.         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!


阅读(5464) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~