简体   繁体   中英

ping test is always returning False

I am running the following ping test and it always returns False. from the cli on the same machine I ping the host and it replies, but when I run the python script it doesnt work. Not sure what I am missing? I have tried to set the number of pings higher and it has no effect. The host is a Debian box. I have removed the suppresion and I see it pinging the host and it is replying, but eventually it returns with a False. I have tried hostnames and IP's.

def myping(host):
    print(f"pinging {host}")
    response = subprocess.run(["ping", "-c", "2", f"{host}"])
               #stdout=subprocess.DEVNULL,
               #stderr=subprocess.STDOUT)

print(myping("10.21.30.2"))

response with a valid IP:

pinging 10.21.30.2
PING 10.21.30.2 (10.21.30.2) 56(84) bytes of data.
64 bytes from 10.21.30.2: icmp_seq=1 ttl=64 time=0.478 ms
64 bytes from 10.21.30.2: icmp_seq=2 ttl=64 time=0.476 ms

--- 10.21.30.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1019ms
rtt min/avg/max/mdev = 0.476/0.477/0.478/0.001 ms
False

You need to actually inspect your response and return a value based on whether it indicates that the operation was a success.

As with all Python functions, the default return value is None , which is treated as False when evaluated as a boolean.

def myping(host):
    print(f"pinging {host}")
    response = subprocess.run(["ping", "-c", "2", str(host)])
    return response.returncode == 0

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