Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYTHON PING IP ADDRESS WITH RESULTS

Tags:

python

ping

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) 
like image 277
Jun Avatar asked Mar 15 '26 03:03

Jun


1 Answers

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))
like image 81
Alexander Avatar answered Mar 17 '26 16:03

Alexander