PYTHON PING IP ADDRESS WITH RESULTS

I am using this code to verify the connection of an ip address using python and this code works for me. However, I would like to use this code to return a value if it has connectivity or not with the ip address. How should I do this?

the code here goes like this:

import subprocess import platform ip_addr = '192.168.0.10' def ping(host): """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ # Option for the number of packets as a function of param = '-n' if platform.system().lower()=='windows' else '-c' # Building the command. Ex: "ping -c 1 google.com" command = ['ping', param, '1', host] return subprocess.call(command) == 0 ping(ip_addr) 
2

1 Answer

If you need to capture the output, or just don't like the way you are doing it currently then you could capture stdout and check the output for a failure string. You can capture stdout like this:

def ping(host): param = '-n' if platform.system().lower()=='windows' else '-c' command = ['ping', param, '1', host] result = subprocess.run(command, stdout=subprocess.PIPE) output = result.stdout.decode('utf8') if "Request timed out." in output or "100% packet loss" in output: return "NOT CONNECTED" return "CONNECTED" print(ping(ip_addr)) 
3

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmxrYWp9d4SOqbCtoJ%2BjerG1zaBkoqhdlrGlvsSsqmavmam1br7ErKylrKM%3D

ncG1vNJzZmilnJ23b63MrGpnnJmctrWty6ianpmeqL2ir8SsZZynnWS9usDHqKVmqJmjtG61z2aYnZyimsC0edaiq6FloprAtrjTrGWhrJ2h