簡體   English   中英

在Linux中結合兩個ping命令

[英]Combining two ping command in Linux

我有兩個有效的命令,用於檢查設備的啟動/關閉並復制丟包值。

用於上下檢查設備

 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腳本已更新。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM