我有两个工作命令,检查设备启动/关闭和复制数据包丢失值。
为了检查我使用的设备上下
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
关于python - 在 Linux 中结合两个 ping 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799978/