用Python Ping站点?

2024-04-25 12:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

看这个pure Python pingMatthew Dixon CowlesJens Diemer。另外,请记住,Python需要根来生成linux中的ICMP(即ping)套接字。

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

源代码本身很容易阅读,请参阅verbose_pingPing.do的实现以获得灵感。

您可以找到Noah Gift's演示文稿Creating Agile Commandline Tools With Python。在它中,他结合了子流程、队列和线程来开发能够并发ping主机并加快进程的解决方案。下面是在添加命令行解析和一些其他特性之前的基本版本。可以找到此版本和其他版本的代码here

#!/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()

他也是Python for Unix and Linux System Administration的作者

http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

根据您想要实现的目标,您可能最容易调用系统ping命令。。

使用subprocess模块是最好的方法,尽管您必须记住ping命令在不同的操作系统上是不同的!

import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out

您不必担心shell转义字符。例如。。

host = "google.com; `echo test`

…将不执行echo命令。

现在,要实际获得ping结果,可以解析out变量。示例输出:

round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms

正则表达式示例:

import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')

同样,请记住输出将根据操作系统(甚至是ping的版本)而变化。这并不理想,但它在许多情况下都可以正常工作(您知道脚本将在哪些机器上运行)

相关问题 更多 >