用Python实现ping远程主机的工具

由于需要维护的机器比较多,有时需要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,就认为没有响应

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhao_rock_2016

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值