【问题标题】:Combining two ping command in Linux在 Linux 中结合两个 ping 命令
【发布时间】:2016-11-25 07:44:07
【问题描述】:

我有两个工作命令来检查设备向上/向下和复制丢包值。

用于检查我使用的设备

 result = os.system ("ping -c 5 " +hostname)

为了复制丢包值,我使用了

packetloss = os.popen ("ping -c 5 " +hostname+ "| grep -oP '\d+(?=% packet loss)'").read().rstrip()
packetloss = int(packetloss)

我知道使用 os.system 是不切实际的。我的问题是如何结合这两个命令?现在我需要 ping 两次才能启动/关闭设备,然后再 ping 一次来检查数据包丢失值。我怎样才能 ping 一次以获得两个结果?

【问题讨论】:

    标签: python linux terminal


    【解决方案1】:

    使用子进程。然后就可以直接解析出你需要的字符串了。

    编辑: python 脚本已更新。

    import subprocess
    
    output = ""
    error = ""
    hostname = "www.google.com"
    try:
        cmd = "ping -c 5 " + hostname
        p = subprocess.Popen([cmd], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
        output = str(p[0])
        error = str(p[1])
    except Exception, e:
        error = str(e)
    
    if output:
        data = output.split("--- " + hostname + " ping statistics ---")
        print "\nPing output:\n", data[0].strip() 
        statistics = data[-1].strip()
        print "\nStatistics:\n", statistics
        packetloss = str(statistics.splitlines()[0]).split(",")
        packetloss = packetloss[2].strip()
        packetloss = packetloss[:packetloss.find("%")]
        print "\nPacketLoss:", packetloss
    if error:
        print "\nError:", error
    

    【讨论】:

    • 我对字符串没有问题。我只是想通过将两个 ping 命令组合成单个命令来节省时间。即使我喜欢上面的方法,就像你说的用 ping -c -5 主机名替换它,但最后我仍然需要 ping 两次才能得到两个不同的结果
    • 使用上述命令仍然 ping 地址两次。是否可以通过一次 ping 来获取设备启动/关闭和丢包值?
    • @Jack 对不起,我不明白这个one time ping to get device up/down and packet loss value? 但我知道你只需要ping 输出ping -c 5 + hostname 并且你需要找到PacketLoss,对吗?如果是这样,那你为什么要 ping 两次?只需使用 python 解析字符串,而不是使用grep。这应该是简单的方法。如果不是,那么只需发布您需要的输出。
    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2018-07-07
    • 2022-07-06
    • 2015-01-30
    • 2014-08-15
    • 2019-03-21
    • 2015-01-29
    • 2022-01-07
    相关资源
    最近更新 更多