简体   繁体   中英

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. 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 , then also it says Online when in actual it should be Offline .

Another solution I tried is checking the output of ping command:

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 . This solution works well in all cases but sometime it throws error 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 .

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 . Can anyone please help me. Thanks

Check out the scapy python library.

The first example here would give you some insights on how to solve the ping problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM