10

サーバーのIPアドレスのリストがあります。それぞれがオンラインであるかどうか、および待ち時間の長さを確認する必要があります。

これを実装する簡単な方法は見つかりませんでした。レイテンシを正確に計算するには、いくつかの問題があるようです。


何か案は?

4

6 に答える 6

7

文字列の解析に既に慣れている場合は、サブプロセスモジュールを使用して、次のように、探しているデータを文字列に変換できます。

>>> 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
于 2010-03-26T17:45:11.413 に答える
5

fpingを使用するというhlovdalの提案に従って、プロキシのテストに使用するソリューションを次に示します。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
于 2012-12-27T12:46:07.290 に答える
3

すべてのネットワーク通信の詳細を実装することを避けたい場合は、おそらくfpingの上に何かを構築しようとすることができます。

fpingは、インターネット制御メッセージプロトコル(ICMP)エコー要求を使用して、ターゲットホストが応答しているかどうかを判断する同様のプログラムです。fpingはpingとは異なり、コマンドラインで任意の数のターゲットを指定したり、pingするターゲットのリストを含むファイルを指定したりできます。タイムアウトまたは応答するまで1つのターゲットに送信する代わりに、fpingはpingパケットを送信し、ラウンドロビン方式で次のターゲットに移動します。

于 2010-03-26T17:44:55.173 に答える
2

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

于 2015-01-27T15:52:56.703 に答える
1

Jabbaに感謝しますが、そのコードは私には正しく機能しないので、次のように変更します

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()
于 2018-02-19T15:47:57.847 に答える
1

この投稿は少し古く、今日はもっと良い方法があると思います。私は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/

于 2021-07-19T14:28:31.737 に答える