#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue
num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
"""Pings subnet"""
while True:
ip = q.get()
print "Thread %s: Pinging %s" % (i, ip)
ret = subprocess.call("ping -c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
if ret == 0:
print "%s: is alive" % ip
else:
print "%s: did not respond" % ip
q.task_done()
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=pinger, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in ips:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
看这个pure Python ping由Matthew Dixon Cowles和Jens Diemer。另外,请记住,Python需要根来生成linux中的ICMP(即ping)套接字。
源代码本身很容易阅读,请参阅
verbose_ping
和Ping.do
的实现以获得灵感。您可以找到Noah Gift's演示文稿Creating Agile Commandline Tools With Python。在它中,他结合了子流程、队列和线程来开发能够并发ping主机并加快进程的解决方案。下面是在添加命令行解析和一些其他特性之前的基本版本。可以找到此版本和其他版本的代码here
他也是Python for Unix and Linux System Administration的作者
http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg
根据您想要实现的目标,您可能最容易调用系统ping命令。。
使用subprocess模块是最好的方法,尽管您必须记住ping命令在不同的操作系统上是不同的!
您不必担心shell转义字符。例如。。
…将不执行echo命令。
现在,要实际获得ping结果,可以解析
out
变量。示例输出:正则表达式示例:
同样,请记住输出将根据操作系统(甚至是
ping
的版本)而变化。这并不理想,但它在许多情况下都可以正常工作(您知道脚本将在哪些机器上运行)相关问题 更多 >
编程相关推荐