如何在 python 中保存 ping 输出
How to save ping output in python
我有以下代码 returns 设备的 ping 状态:
def ping_check(hostname):
response = os.system("ping -c 3 " + hostname)
if response == 0:
pingstatus = "Online"
else:
pingstatus = "Offline"
return pingstatus
这很好用并且按预期工作。但是,我想将 ping 输出保存到一个变量中,但我不确定该怎么做。
输出现在看起来像这样:
>>> hostname = "google.com"
>>> op = os.system("ping -c 3 " + hostname)
PING google.com (172.217.7.206) 56(84) bytes of data.
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=1 ttl=48 time=1.56 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=2 ttl=48 time=1.57 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=3 ttl=48 time=1.52 ms
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2012ms
rtt min/avg/max/mdev = 1.526/1.552/1.572/0.049 ms
>>>
我想将 ping 的实际输出保存到一个变量中,这样我就可以把它放到某个东西中以备后用。非常感谢任何帮助。
您可以使用 subprocess.check_output
:
import subprocess
output = subprocess.check_output(["ping","-c","3",hostname])
请注意 return 值的类型为 bytes
。
我有以下代码 returns 设备的 ping 状态:
def ping_check(hostname):
response = os.system("ping -c 3 " + hostname)
if response == 0:
pingstatus = "Online"
else:
pingstatus = "Offline"
return pingstatus
这很好用并且按预期工作。但是,我想将 ping 输出保存到一个变量中,但我不确定该怎么做。
输出现在看起来像这样:
>>> hostname = "google.com"
>>> op = os.system("ping -c 3 " + hostname)
PING google.com (172.217.7.206) 56(84) bytes of data.
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=1 ttl=48 time=1.56 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=2 ttl=48 time=1.57 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=3 ttl=48 time=1.52 ms
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2012ms
rtt min/avg/max/mdev = 1.526/1.552/1.572/0.049 ms
>>>
我想将 ping 的实际输出保存到一个变量中,这样我就可以把它放到某个东西中以备后用。非常感谢任何帮助。
您可以使用 subprocess.check_output
:
import subprocess
output = subprocess.check_output(["ping","-c","3",hostname])
请注意 return 值的类型为 bytes
。