ori*_*rip 77
看到这个纯Python平由马修·考尔斯迪克森和延DIEMER.另外,请记住Python需要root才能在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
Run Code Online (Sandbox Code Playgroud)
源代码本身易于阅读,请参阅实现verbose_ping和Ping.do获取灵感.
dbr*_*dbr 40
根据您想要获得的内容,您可能最容易调用系统ping命令.
使用子进程模块是执行此操作的最佳方法,但您必须记住不同操作系统上的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
Run Code Online (Sandbox Code Playgroud)
您不必担心shell转义字符.例如..
host = "google.com; `echo test`
Run Code Online (Sandbox Code Playgroud)
.. 不会执行echo命令.
现在,要实际获取ping结果,您可以解析out变量.示例输出:
round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
Run Code Online (Sandbox Code Playgroud)
示例正则表达式:
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')
Run Code Online (Sandbox Code Playgroud)
同样,请记住输出将根据操作系统(甚至版本ping)而有所不同.这不是理想的,但它可以在许多情况下正常工作(你知道脚本将运行的机器)
Rya*_*Cox 39
您可能会发现Noah Gift的演示文稿 使用Python创建敏捷命令行工具.在其中,他结合了子进程,队列和线程来开发能够同时ping主机并加快进程的解决方案.下面是他添加命令行解析和其他一些功能之前的基本版本.可以在此处找到此版本和其他代码
#!/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()
Run Code Online (Sandbox Code Playgroud)
他还是:Unix for Unix和Linux System Administration的作者
http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg
很难说你的问题是什么,但也有一些选择.
如果您要使用ICMP ping协议逐字执行请求,则可以获取ICMP库并直接执行ping请求.Google"Python ICMP"可以找到像这样的icmplib.你也许想看看scapy.
这将比使用快得多os.system("ping " + ip ).
如果你的意思是通常"ping"一个盒子以查看它是否已启动,你可以在端口7上使用echo协议.
对于echo,使用套接字库打开IP地址和端口7.您在该端口上写入内容,发送回车符("\r\n")然后阅读回复.
如果您要"ping"网站以查看该网站是否正在运行,则必须在端口80上使用http协议.
要正确检查Web服务器,请使用urllib2打开特定URL.(/index.html总是很受欢迎)并阅读回复.
"ping"还有更多潜在的意义,包括"traceroute"和"finger".
我做了类似的事情,作为灵感:
import urllib
import threading
import time
def pinger_urllib(host):
"""
helper function timing the retrival of index.html
TODO: should there be a 1MB bogus file?
"""
t1 = time.time()
urllib.urlopen(host + '/index.html').read()
return (time.time() - t1) * 1000.0
def task(m):
"""
the actual task
"""
delay = float(pinger_urllib(m))
print '%-30s %5.0f [ms]' % (m, delay)
# parallelization
tasks = []
URLs = ['google.com', 'wikipedia.org']
for m in URLs:
t = threading.Thread(target=task, args=(m,))
t.start()
tasks.append(t)
# synchronization point
for t in tasks:
t.join()
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个简短的片段subprocess.该check_call方法要么返回0表示成功,要么引发异常.这样,我不必解析ping的输出.我正在使用shlex拆分命令行参数.
import subprocess
import shlex
command_line = "ping -c 1 www.google.comsldjkflksj"
args = shlex.split(command_line)
try:
subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print "Website is there."
except subprocess.CalledProcessError:
print "Couldn't get a ping."
Run Code Online (Sandbox Code Playgroud)
小智 6
我开发了一个我认为可以帮助你的库。它称为 icmplib(与 Internet 上可以找到的任何其他同名代码无关),是 ICMP 协议在 Python 中的纯粹实现。
它完全面向对象,具有简单的功能,例如经典的 ping、multiping 和 Traceroute,以及低级类和套接字,适合那些想要开发基于 ICMP 协议的应用程序的人。
以下是其他一些亮点:
安装它(需要 Python 3.6+):
pip3 install icmplib
Run Code Online (Sandbox Code Playgroud)
下面是 ping 功能的一个简单示例:
host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)
if host.is_alive:
print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
else:
print(f'{host.address} is dead')
Run Code Online (Sandbox Code Playgroud)
如果您想在没有 root 权限的情况下使用该库,请将“privileged”参数设置为 False。
您可以在项目页面上找到完整的文档: https://github.com/ValentinBELYN/icmplib
希望您会发现这个库很有用。
| 归档时间: |
|
| 查看次数: |
209522 次 |
| 最近记录: |