今天群里有个童鞋问到我想用python来写一个ping检查多台主机健康状态的一个脚本,还真没写过。然后我就试着写了一下,因为我的python也属于学习阶段所以
还是要借助于好多资料才写成的,当然里面还需要有好多的优化,只是简单的实现了,还请各位多多指出问题,多谢!
新增了一个打开要检查文件列表的功能,输入你要检查的机器的列表文件名.
代码:
-
#!/usr/bin/env python
-
#Auther:XaoSa
-
import os,sys,re
-
import subprocess
-
def runCheck(source):
-
file_obj = open(source)
-
for host in file_obj.readlines():
-
host = host.strip('\n')
-
p = subprocess.Popen(["ping -c 1 "+ host],
-
stdin = subprocess.PIPE,
-
stdout = subprocess.PIPE,
-
stderr = subprocess.PIPE,
-
shell = True)
-
out = p.stdout.read()
-
regex = re.compile("time=\d*", re.IGNORECASE | re.MULTILINE)
-
if len(regex.findall(out)) > 0:
-
print host+': Host Up!'
-
else:
-
print host+': Host Down!'
-
-
def Usage():
-
print """ ---Need to enter an absolute path---
-
---(The current directory except)---"""
-
-
while True:
-
Usage()
-
source = raw_input('Please input your check_host_list_file:')
-
if os.path.exists(source):
-
runCheck(source)
-
exit()
-
-
elif source == 'ls':
-
print '--------List current directory--------'
-
os.system('ls')
-
-
else:
-
print "Sorry your check_host_list_file not exist!"
-
192.168.3.88 :Host up!
-
192.168.3.12 :Host up!
-
192.168.3.123 :Host down!
-
192.168.3.44 :Host up!
阅读(5502) | 评论(0) | 转发(0) |