[英]How to check the status of ping in python
I am working on python project where I need to ping an ip address
to check if it online or offline.我正在处理 python 项目,我需要 ping ip address
以检查它是在线还是离线。 For this I have referred to most of the questions and answers online.为此,我参考了网上的大部分问题和答案。 Below is what I have tried first:以下是我首先尝试过的:
response = os.system("ping -c 1 " + ip_address)
if response == 0:
print("Online")
else:
print("Offline")
Above approach works fine but if we have Reply from <ip>. Destination host unreachable
上述方法工作正常,但如果我们有Reply from <ip>. Destination host unreachable
Reply from <ip>. Destination host unreachable
, then also it says Online
when in actual it should be Offline
. Reply from <ip>. Destination host unreachable
,然后它也说Online
而实际上它应该是Offline
。
Another solution I tried is checking the output of ping command:我尝试的另一个解决方案是检查 ping 命令的 output:
cmd = "ping -c 1 " + ip_address
res = (subprocess.check_output(cmd, shell=True))
res = res.decode("utf-8")
if 'unreachable' in res or 'timed out' in res or '100% packet loss' in res:
print("Offline")
else:
print("Online")
In this approach I am checking if the response contains unreachable
or timed out
or 100% packet loss
(only in case of linux), then I am saying that its Offline
or else Online
.在这种方法中,我正在检查响应是否包含unreachable
或timed out
或100% packet loss
(仅在 linux 的情况下),然后我说它的Offline
或Online
。 This solution works well in all cases but sometime it throws error Command 'ping -c 1 <ip>' returned non-zero exit status 1.
此解决方案在所有情况下都运行良好,但有时会引发错误Command 'ping -c 1 <ip>' returned non-zero exit status 1.
I also need to make sure that code I am writing should work both on Windows
and Ubuntu
.我还需要确保我正在编写的代码可以在Windows
和Ubuntu
上运行。
I am not able to understand on what is the cleanest and simplest way of checking the response of ping and deciding if Online
or Offline
.我无法理解检查 ping 响应并决定是Online
还是Offline
的最干净和最简单的方法是什么。 Can anyone please help me.谁能帮帮我吗。 Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.