Python中的多个ping脚本

时间:2012-08-23 23:09:43

标签: python networking ping

我无法在python和网络上找到任何好的易学文档。在这个例子中,我只是想制作一个简单的脚本,我可以ping许多远程机器。

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

这样一个简单的脚本可以很好地ping机器,但是我想让脚本返回'active''没有响应'这让我觉得我还要查看时间模块,我想time.sleep(5),然后会有一个中断声明。这让我觉得里面应该有一个while循环。我不是百分百肯定,我可能会完全朝着错误的方向前进:/如果有人可以提供帮助,或者指向一些非常棒的文档。

9 个答案:

答案 0 :(得分:26)

试试subprocess.call。它保存了所使用程序的返回值。

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

# 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!"

答案 1 :(得分:10)

这个脚本:

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(1, 10):
                ip="192.168.0.{0}".format(n)
                result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

会产生类似这样的输出:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

如果将limbo替换为subprocess.PIPE并使用communicate()对象上的Popen,则可以捕获输出:

p=Popen( ... )
output=p.communicate()
result=p.wait()

这样您就可以获得命令的返回值并捕获文本。在manual之后,如果您需要灵活性,这是操作子流程的首选方法:

  

此模块中的基础流程创建和管理是   由Popen班级处理。它提供了很大的灵活性   开发人员能够处理不常见的案例   便利功能。

答案 2 :(得分:5)

非常感谢你。我已将其修改为与Windows一起使用。我也设置了一个低超时,所以没有返回的IP将不会等待5秒钟。这是来自hochl源代码。

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(200, 240):
                ip="10.2.7.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

只需更改您的方案的ip =和主机的xrange。

答案 3 :(得分:4)

我是初学者并编写了一个脚本来ping多个主机。要ping多个主机,您可以使用ipaddress模块​​。

import ipaddress
from subprocess import Popen, PIPE

net4 = ipaddress.ip_network('192.168.2.0/24')
for x in net4.hosts():
    x = str(x)
    hostup = Popen(["ping", "-c1", x], stdout=PIPE)
    output = hostup.communicate()[0]
    val1 = hostup.returncode
 if val1 == 0:
    print(x, "is pinging")
 else:
    print(x, "is not responding")

答案 4 :(得分:2)

要同时ping多个主机,您可以使用subprocess.Popen()

#!/usr/bin/env python3
import os
import time
from subprocess import Popen, DEVNULL

p = {} # ip -> process
for n in range(1, 100): # start ping processes
    ip = "127.0.0.%d" % n
    p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL)
    #NOTE: you could set stderr=subprocess.STDOUT to ignore stderr also

while p:
    for ip, proc in p.items():
        if proc.poll() is not None: # ping finished
            del p[ip] # remove from the process list
            if proc.returncode == 0:
                print('%s active' % ip)
            elif proc.returncode == 1:
                print('%s no response' % ip)
            else:
                print('%s error' % ip)
            break

如果您可以作为root运行,则可以使用pure Python ping scriptscapy

from scapy.all import sr, ICMP, IP, L3RawSocket, conf

conf.L3socket = L3RawSocket # for loopback interface
ans, unans = sr(IP(dst="127.0.0.1-99")/ICMP(), verbose=0) # make requests
ans.summary(lambda (s,r): r.sprintf("%IP.src% is alive"))

答案 5 :(得分:1)

import subprocess
import os
'''
servers.txt contains ip address in following format
192.168.1.1
192.168.1.2
'''
    with open('servers.txt', 'r') as f:
        for ip in f:
            result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2",    ip],stdout=f, stderr=f).wait()
            if result:
                print(ip, "inactive")
            else:
                print(ip, "active")

答案 6 :(得分:0)

Python实际上有一个非常甜蜜的method,它将在网络中的可用主机上返回一个迭代器'。 (将strict设置为false会迭代所有IP)

例如:

import subprocess
import ipaddress

subnet = ipaddress.ip_network('192.168.1.0/24', strict=False)
for i in subnet.hosts():
    i = str(i)
    subprocess.call(["ping", "-c1", "-n", "-i0.1", "-W1", i])

等待间隔(-i0.1)对于自动化可能很重要,即使一秒超时(-t1)也可能永远超过.0 / 24

修改: 因此,为了跟踪ICMP(ping)请求,我们可以这样做:

#!/usr/bin/env python

import subprocess
import ipaddress

alive = []
subnet = ipaddress.ip_network('192.168.1.0/23', strict=False)
for i in subnet.hosts():
    i = str(i)
    retval = subprocess.call(["ping", "-c1", "-n", "-i0.1", "-W1", i])
    if retval == 0:
        alive.append(i)
for ip in alive:
    print(ip + " is alive") 

将返回类似的内容:

192.168.0.1 is alive
192.168.0.2 is alive
192.168.1.1 is alive
192.168.1.246 is alive

即。所有响应ICMP的IP都在整个/ 23--非常酷!

答案 7 :(得分:0)

我在python 2.7中使用多线程对上面的代码做了一些修改:

import subprocess,os,threading,time
import Queue

lock=threading.Lock()
_start=time.time()
def check(n):
    with open(os.devnull, "wb") as limbo:
                ip=n
                result=subprocess.Popen(["ping", "-n", "2", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()
                with lock:
                    if not result:
                        print ip, "active"
                    else:
                        print ip, "Inactive"

def threader():
    while True:
        worker=q.get()
        check(worker)
        q.task_done()
q = Queue.Queue()

for x in range(255):
    t=threading.Thread(target=threader)
    t.daemon=True
    t.start()

ip = ["13.45.23.523", "13.35.23.523","23.23.56.346"]
for worker in ip:
    q.put(worker)
q.join()
print("Process completed in: ",time.time()-_start)

答案 8 :(得分:-1)

import subprocess,os,threading,time
from queue import Queue
lock=threading.Lock()
_start=time.time()
def check(n):
    with open(os.devnull, "wb") as limbo:
                ip="192.168.21.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()
                with lock:                    
                    if not result:
                        print (ip, "active")                    
                    else:
                        pass                        

def threader():
    while True:
        worker=q.get()
        check(worker)
        q.task_done()
q=Queue()

for x in range(255):
    t=threading.Thread(target=threader)
    t.daemon=True
    t.start()
for worker in range(1,255):
    q.put(worker)
q.join()
print("Process completed in: ",time.time()-_start)

我认为这会更好。