3

您将如何解析“ping”输出,如下所示:

root@m2m-probe1:~/M2M/src# ping -c 20 -q google.es
PING google.es (173.194.34.247) 56(84) bytes of data.

--- google.es ping statistics ---
20 packets transmitted, 20 received, 0% packet loss, time 19043ms
rtt min/avg/max/mdev = 314.766/381.299/430.826/36.513 ms

用 Python 吗?到目前为止,我发现的更好的是:

output = subprocess.check_output('ping ' + host + " -c 5 -q  | egrep \"packet loss|rtt\"", shell=True)

match = re.search('([\d]*\.[\d]*)/([\d]*\.[\d]*)/([\d]*\.[\d]*)/([\d]*\.[\d]*)', output)

ping_min = match.group(1)
ping_avg = match.group(2)
ping_max = match.group(3)

match = re.search('(\d*)% packet loss', output)
pkt_loss = match.group(1)

它有效,但我知道它远非实现它的最佳方式。有什么建议吗?

提前致谢!

4

2 回答 2

3

已经有一个纯 python 模块可以做到这一点https://github.com/gg/pingparser,但是如果你想为教学目的实现它,请使用 pyparsing 库。它比解析数据的正则表达式要好得多。

于 2013-07-01T15:24:31.707 回答
1

我没有找到正则表达式,可能是因为我使用得不够多......

output = subprocess.check_output('ping -c %s -W %s -t %s 8.8.8.8' % (self.numPings, (self.pingTimeout * 1000), self.maxWaitTime), shell=True)

output = output.split('\n')[-3:]
# -1 is a blank line, -3 & -2 contain the actual results

xmit_stats = output[0].split(",")
timing_stats = output[1].split("=")[1].split("/")

packet_loss = float(xmit_stats[2].split("%")[0])

ping_min = float(timing_stats[0])
ping_avg = float(timing_stats[1])
ping_max = float(timing_stats[2])
于 2016-02-06T15:22:01.230 回答