Rad*_*Hex 6 python networking tcp latency
我有一个服务器IP地址列表,我需要检查每个服务器IP地址是否在线以及延迟时间.
我还没有找到任何直接的实现方法,并且在准确计算延迟方面似乎存在一些问题.
有任何想法吗?
如果您已经熟悉解析字符串,则可以使用子进程模块将要查找的数据转换为字符串,如下所示:
>>> import subprocess
>>> p = subprocess.Popen(["ping.exe","www.google.com"], stdout = subprocess.PIPE)
>>> print p.communicate()[0]
Pinging www.l.google.com [209.85.225.99] with 32 bytes of data:
Reply from 209.85.225.99: bytes=32 time=59ms TTL=52
Reply from 209.85.225.99: bytes=32 time=64ms TTL=52
Reply from 209.85.225.99: bytes=32 time=104ms TTL=52
Reply from 209.85.225.99: bytes=32 time=64ms TTL=52
Ping statistics for 209.85.225.99:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 59ms, Maximum = 104ms, Average = 72ms
Run Code Online (Sandbox Code Playgroud)
按照hlovdal 建议使用fping,这是我用于测试代理的解决方案。我只在Linux下试过。如果无法测量到 ping 时间,则返回一个大值。用法:print get_ping_time('<ip>:<port>')
。
import shlex
from subprocess import Popen, PIPE, STDOUT
def get_simple_cmd_output(cmd, stderr=STDOUT):
"""
Execute a simple external command and get its output.
"""
args = shlex.split(cmd)
return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0]
def get_ping_time(host):
host = host.split(':')[0]
cmd = "fping {host} -C 3 -q".format(host=host)
res = [float(x) for x in get_simple_cmd_output(cmd).strip().split(':')[-1].split() if x != '-']
if len(res) > 0:
return sum(res) / len(res)
else:
return 999999
Run Code Online (Sandbox Code Playgroud)
小智 5
这篇文章有点旧了,我认为今天存在更好的方法。我是 python 新手,但这是我在项目中所做的:
from pythonping import ping
def ping_host(host):
ping_result = ping(target=host, count=10, timeout=2)
return {
'host': host,
'avg_latency': ping_result.rtt_avg_ms,
'min_latency': ping_result.rtt_min_ms,
'max_latency': ping_result.rtt_max_ms,
'packet_loss': ping_result.packet_loss
}
hosts = [
'192.168.48.1',
'192.168.48.135'
]
for host in hosts:
print(ping_host(host))
Run Code Online (Sandbox Code Playgroud)
结果:
{'host': '192.168.48.1', 'avg_latency': 2000.0, 'min_latency': 2000, 'max_latency': 2000, 'packet_loss': 1.0}
{'host': '192.168.48.135', 'avg_latency': 42.67, 'min_latency': 41.71, 'max_latency': 44.17, 'packet_loss': 0.0}
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到 pythonping 库:https ://pypi.org/project/pythonping/
归档时间: |
|
查看次数: |
24465 次 |
最近记录: |