使用 Python 显示 ping 信息

Show ping information using Python

我正在从我的计算机 (windows) ping 另一台计算机 (windows)。我正在使用 Python 代码。我的代码如下

import os
hostname = "192.168.1.2"
response = os.system ("ping -c 5 " +hostname)

if response ==0:
    print(hostname, "is up")
else:
    print(hostname, "is down")

我得到了这样的输出

PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
64 bytes from 192.168.1.2: icmp_seq=1 ttl=128 time=1.47 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=128 time=0.816 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=128 time=0.584 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=128 time=0.749 ms
64 bytes from 192.168.1.2: icmp_seq=5 ttl=128 time=0.601 ms

--- 192.168.1.2 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4003ms
rtt min/avg/max/mdev = 0.584/0.844/1.470/0.325 ms
('192.168.1.2', 'is up')

统计信息后如何设置成这样?

Highest ping is 200 and lowest ping 40
('192.168.1.2', 'is up')

Ping is too high. consider reboot the network
('192.168.1.2', 'is up')
response = os.system ("ping -n 5 " +hostname)

即使其无法访问的响应也将是 0。只有IP错误才会return 1

你可能会选择类似于

的东西
try:
    response = subprocess.check_output("ping -n 5"+hostname)
    print response

    if "Destination host unreachable" in response:
        print hostname+" unreachable"

    else:
        print hostname+" Running"
    print '\n'.join(response.split('\n')[8:]) 

except:
    print "Invalid Hostname"

根据关键词判断是否可达!!

输出:

<hostname> Running
Ping statistics for <hostname>:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

        Minimum = 1ms, Maximum = 1ms, Average = 1ms

一般情况下,您有两种选择。您可以捕获外部命令的输出(使用 subprocess module that's in the Python standard libraries) or you can use some code (a third party module) which implements "ping" (ICMP ECHO REQUEST) from within your Python code. There are a few of these listed on PyPI(规范的 Python 包索引):

pyping 是旧的,它的 GitHub link 已经永远被破坏了……但是代码仍然可以直接从 PyPI 获得并且它仍然有效;我似乎记得我还必须应用一些小的修复程序才能将其用作库而不是命令行实用程序)。

ping 甚至更老(最后一次更新是 2010 年)...但它的存储库仍然存在于 Bitbucket 上。

python3-ping is the most recent, and requires Python3. It's GitHub: python3-ping 已上线,但已经有几年没有更新了。 (可能 none 已被要求......也没有任何未完成的拉取请求)。

如果您在 PyPI 中搜索其他替代品,那么我建议您使用 ICMP 作为搜索词。在 "ping" 上搜索会为您找到涉及 "mapping" 和 "scraping" 等的每个包——这相当于相当多的不相关匹配项。

请注意,后一种方法在纯 Python 中重新实现 ICMP 处理,需要 运行将您的 Python 代码设置为 root(在 Unix/Linux 上)或在 MS Windows 中拥有 "Administrator" 权限。那是因为 ICMP 数据包必须通过 "raw" 套接字发送......并且由于一些原因而享有特权(包括一些其他类型的 ICMP 数据包,它们会影响网络如何处理您的整个系统而不仅仅是进程,套接字,你正在使用)。 (这里是 Raw Socket Programming in Python 的指南以获取更多信息)。

在前一种情况下,您捕获命令的输出,对其进行解析,然后将其与其他文本一起打印出来。该方法的一个问题是您的用户在默认情况下不会看到任何输出,直到整个程序执行并退出(所有五个 ping 响应都已收到或超时)。如果您愿意,您可以通过使用无缓冲 I/O 来解决这个问题......在子进程发出它时捕获每一行输出并在子进程的输出管道上执行下一个 read() 之前将其中继出去。在后一种情况下,您对执行流程有更细粒度的控制......您甚至可以 运行 多个线程同时 ping 多个目标,等等