Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6874171
  • 博文数量: 3857
  • 博客积分: 6409
  • 博客等级: 准将
  • 技术积分: 15948
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-02 16:48
个人简介

迷彩 潜伏 隐蔽 伪装

文章分类

全部博文(3857)

文章存档

2017年(5)

2016年(63)

2015年(927)

2014年(677)

2013年(807)

2012年(1241)

2011年(67)

2010年(7)

2009年(36)

2008年(28)

分类: Python/Ruby

2013-04-11 15:54:46

今天群里有个童鞋问到我想用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!


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