获取 python 中 ping 命令接收到的数据包数

Get number of packets received by ping command in python

我需要一个可以 return 接收到的数据包数量或丢失百分比的函数。在我使用下面的代码获取 true/false 之前,如果我收到任何数据包。这应该适用于 Windows,但如果有人也能做到适合 Linux,我将不胜感激。

def ping_ip(ip):
    current_os = platform.system().lower()
    parameter = "-c"
    if current_os == "windows":
        parameter = "-n"

    command = ['ping', parameter, '4', ip]

    res = subprocess.call(command)
    return res == 0

这是我的解决方案 - 只需执行 ping 命令的标准输出并对其进行分析。

def ping_ip(ip):
    res = 0
    current_os = platform.system().lower()
    parameter = "-c"
    if current_os == "windows":
        parameter = "-n"

    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    command = ['ping', parameter, '4', ip]
    process = subprocess.Popen(command, startupinfo=si, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    percentage = 0

    f = process.stdout.read().decode('ISO-8859-1').split()
    for x in f:
        if re.match(r".*%.*", x):
            strArr = []
            strArr[:0] = x
            strArr = strArr[1:-1]
            listToStr = ''.join(map(str, strArr))
            percentage = int(listToStr)
    if percentage == 0:
        res = 0  # 0% loss
    elif percentage == 100:
        res = 1  # 100% loss
    else:
        res = 2  # partial loss
    return res