Python中的多个ping脚本 [英] Multiple ping script in Python

查看:290
本文介绍了Python中的多个ping脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到关于python和网络的任何易于学习的文档.在这种情况下,我只是试图制作一个简单的脚本,可以对许多远程计算机执行ping操作.

I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines.

for ping in range(1,10):
   ip="127.0.0."+str(ping)
   os.system("ping -c 3 %s" % ip)

像这样的简单脚本可以使计算机正常运行,但是我想让脚本返回活动"无响应",这让我觉得我也必须查找时间模块,我想想time.sleep(5),然后将有一个break语句.这让我觉得里面应该有一个while循环.我不是100%肯定的,我可能会完全走错了方向://如果有人可以帮助我或将我指向一些很棒的文档的方向.

A simple script like that will ping the machines fine, but I'd like to get the script to returns 'active' 'no response' Which makes me think I'll have to look up the time module as well, I think time.sleep(5) and after that, there would be a break statement. Which makes me think there should be a while loop inside for. I'm not 100% sure, I could be going in the wrong direction completely :/ if anyone could help or point me in the direction of some documentation that'd be great.

推荐答案

尝试subprocess.call.保存使用的程序的返回值.

Try subprocess.call. It saves the return value of the program that was used.

根据我的ping手册,成功返回0,发送ping但未收到回复时返回2,其他任何值表示错误.

According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.

# typo error in import
import subprocess

for ping in range(1,10):
    address = "127.0.0." + str(ping)
    res = subprocess.call(['ping', '-c', '3', address])
    if res == 0:
        print "ping to", address, "OK"
    elif res == 2:
        print "no response from", address
    else:
        print "ping to", address, "failed!"

这篇关于Python中的多个ping脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆