测量服务器的 ping 延迟 - Python

发布于 2024-08-26 07:59:54 字数 149 浏览 8 评论 0原文

我有一个服务器IP 地址列表,我需要检查每个服务器是否在线以及延迟有多长。

我还没有找到任何直接的方法来实现这一点,并且在准确计算延迟方面似乎存在一些问题。


有什么想法吗?

I have a list of server IP addresses, I need to check if each one is online and how long the latency is.

I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.


Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

心如荒岛 2024-09-02 07:59:54

如果您已经熟悉解析字符串,则可以使用 subprocess 模块将您要查找的数据获取到字符串中,如下所示:

>>> 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

If you are already comfortable with parsing strings, you can use the subprocess module to get the data you are looking for into a string, like this:

>>> 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
吝吻 2024-09-02 07:59:54

遵循hlovdal的建议fping,这是我用于测试代理的解决方案。我只在Linux下尝试过。如果无法测量 ping 时间,则会返回一个很大的值。用法:print get_ping_time(':')

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

Following hlovdal's suggestion to work with fping, here is my solution that I use for testing proxies. I only tried it under Linux. If no ping time could be measured, a big value is returned. Usage: 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
拥抱我好吗 2024-09-02 07:59:54

这篇文章有点旧了,我认为今天存在更好的方法。我是 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))

结果:

{'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}

您可以在这里找到 pythonping 库: https ://pypi.org/project/pythonping/

This post is a bit old and I think better ways exists today. I'm new to python but here's what I did on my project:

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))

Result:

{'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}

You can find the pythonping library here: https://pypi.org/project/pythonping/

∝单色的世界 2024-09-02 07:59:54

如果您想避免实现所有网络通信细节,您可以尝试在 fping 之上构建一些东西:

fping 是一个类似的程序,它使用
互联网控制消息协议
(ICMP) 回显请求以确定是否
目标主机正在响应。平
与 ping 的不同之处在于您可以
指定任意数量的目标
命令行,或指定文件
包含目标列表
平。而不是发送到一个目标
直到超时或回复,fping 才会发送
发出 ping 数据包并继续
以循环方式下一个目标。

If you want to avoid implementing all the network communication details you could probably try to build something on top of fping:

fping is a like program which uses the
Internet Control Message Protocol
(ICMP) echo request to determine if a
target host is responding. fping
differs from ping in that you can
specify any number of targets on the
command line, or specify a file
containing the lists of targets to
ping. Instead of sending to one target
until it times out or replies, fping will send
out a ping packet and move on to the
next target in a round-robin fashion.

猫性小仙女 2024-09-02 07:59:54

https://github.com/matthieu-lapeyre/network-benchmark 基于我的解决方案关于 FlipperPA 的工作: https://github.com/FlipperPA/latency-tester

import numpy
import pexpect


class WifiLatencyBenchmark(object):
    def __init__(self, ip):
        object.__init__(self)

        self.ip = ip
        self.interval = 0.5

        ping_command = 'ping -i ' + str(self.interval) + ' ' + self.ip
        self.ping = pexpect.spawn(ping_command)

        self.ping.timeout = 1200
        self.ping.readline()  # init
        self.wifi_latency = []
        self.wifi_timeout = 0

    def run_test(self, n_test):
        for n in range(n_test):
            p = self.ping.readline()

            try:
                ping_time = float(p[p.find('time=') + 5:p.find(' ms')])
                self.wifi_latency.append(ping_time)
                print 'test:', n + 1, '/', n_test, ', ping latency :', ping_time, 'ms'
            except:
                self.wifi_timeout = self.wifi_timeout + 1
                print 'timeout'

        self.wifi_timeout = self.wifi_timeout / float(n_test)
        self.wifi_latency = numpy.array(self.wifi_delay)

    def get_results(self):
        print 'mean latency', numpy.mean(self.wifi_latency), 'ms'
        print 'std latency', numpy.std(self.wifi_latency), 'ms'
        print 'timeout', self.wifi_timeout * 100, '%'


if __name__ == '__main__':
    ip = '192.168.0.1'
    n_test = 100

    my_wifi = WifiLatencyBenchmark(ip)

    my_wifi.run_test(n_test)
    my_wifi.get_results()

Github存储库:
https://github.com/matthieu-lapeyre/network-benchmark

https://github.com/matthieu-lapeyre/network-benchmark My solution based on the work of FlipperPA: https://github.com/FlipperPA/latency-tester

import numpy
import pexpect


class WifiLatencyBenchmark(object):
    def __init__(self, ip):
        object.__init__(self)

        self.ip = ip
        self.interval = 0.5

        ping_command = 'ping -i ' + str(self.interval) + ' ' + self.ip
        self.ping = pexpect.spawn(ping_command)

        self.ping.timeout = 1200
        self.ping.readline()  # init
        self.wifi_latency = []
        self.wifi_timeout = 0

    def run_test(self, n_test):
        for n in range(n_test):
            p = self.ping.readline()

            try:
                ping_time = float(p[p.find('time=') + 5:p.find(' ms')])
                self.wifi_latency.append(ping_time)
                print 'test:', n + 1, '/', n_test, ', ping latency :', ping_time, 'ms'
            except:
                self.wifi_timeout = self.wifi_timeout + 1
                print 'timeout'

        self.wifi_timeout = self.wifi_timeout / float(n_test)
        self.wifi_latency = numpy.array(self.wifi_delay)

    def get_results(self):
        print 'mean latency', numpy.mean(self.wifi_latency), 'ms'
        print 'std latency', numpy.std(self.wifi_latency), 'ms'
        print 'timeout', self.wifi_timeout * 100, '%'


if __name__ == '__main__':
    ip = '192.168.0.1'
    n_test = 100

    my_wifi = WifiLatencyBenchmark(ip)

    my_wifi.run_test(n_test)
    my_wifi.get_results()

Github repository:
https://github.com/matthieu-lapeyre/network-benchmark

離人涙 2024-09-02 07:59:54

感谢贾巴,但该代码对我来说无法正常工作,所以我更改了如下内容

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)
    # result = str(get_simple_cmd_output(cmd)).replace('\\','').split(':')[-1].split() if x != '-']
    result = str(get_simple_cmd_output(cmd)).replace('\\', '').split(':')[-1].replace("n'", '').replace("-",
                                                                                                        '').replace(
        "b''", '').split()
    res = [float(x) for x in result]
    if len(res) > 0:
        return sum(res) / len(res)
    else:
        return 999999


def main():
    # sample hard code for test
    host = 'google.com'
    print([host, get_ping_time(host)])

    host = 'besparapp.com'
    print([host, get_ping_time(host)])



if __name__ == '__main__':
    main()

thanks from Jabba but that code doesn't work correctly for me so i change something like following

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)
    # result = str(get_simple_cmd_output(cmd)).replace('\\','').split(':')[-1].split() if x != '-']
    result = str(get_simple_cmd_output(cmd)).replace('\\', '').split(':')[-1].replace("n'", '').replace("-",
                                                                                                        '').replace(
        "b''", '').split()
    res = [float(x) for x in result]
    if len(res) > 0:
        return sum(res) / len(res)
    else:
        return 999999


def main():
    # sample hard code for test
    host = 'google.com'
    print([host, get_ping_time(host)])

    host = 'besparapp.com'
    print([host, get_ping_time(host)])



if __name__ == '__main__':
    main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文