由于需要维护的机器比较多,有时需要ping主机的状态,时间久了就想写个工具,正好在学习python,而且又比较喜欢python跨平台的特点,最终选择python来实现
代码如下:
#!/usr/bin/python
import os
import re
import platform
def validateIP(ipStart,ipEnd):
p = re.compile('([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}')
if p.match(ipStart) and p.match(ipEnd):
if ipStart[:ipStart.rfind(".")] <> ipEnd[:ipEnd.rfind(".")]:
print "Do not support different Net segment"
exit(0)
else:
print "invalid IP Address"
exit(0)
def checkPing(ipStart,ipEnd):
''' create result txt '''
if os.path.isfile("PingHostResult.txt"):
os.remove("PingHostResult.txt")
fp = open("PingHostResult.txt","w")
''' check different os '''
if platform.system() == 'Linux' :
cmd = 'ping -c 4 %s'
else:
cmd = 'ping -n 4 -w 1 %s'
if ipStart == ipEnd :
backInfo = os.system(cmd%ipStart)
if backInfo == 0 :
result = ipStart+' is ok'
else:
result = ipStart+' no response'
fp.writelines(result)
else:
ipMin = ipStart[ipStart.rfind(".")+1:]
ipMax = ipEnd[ipEnd.rfind(".")+1:]
for i in range (int(ipMin),int(ipMax)+1):
targetIp = ipStart[:ipStart.rfind(".")]+"."+str(i)
backInfo = os.system(cmd%targetIp)
if backInfo == 0 :
result = targetIp+' is ok'
else:
result = targetIp+' no response'
fp.writelines(result+os.linesep)
fp.flush()
fp.close()
if __name__ == "__main__":
ipStart = raw_input("PLS input Start ipAddress: ")
ipEnd = raw_input("PLS input End ipAddress: ")
validateIP(ipStart,ipEnd)
checkPing(ipStart,ipEnd)
''' result output'''
for item in open("PingHostResult.txt","r").readlines():
print item
脚本还有很多漏洞和不足,以及不规范之处,希望前辈们能够多多指出!!!
目前遇到的问题:
windows下ping一个已经挂掉了的主机,发出去的包也会收回来,比较迷惑,希望高手能够指点!
暂时的解决办法是指定 -w 1 等待时间超过1s,就认为没有响应