Skip to content
Advertisement

Ping command – Check returned value

How can I evaluate the return of ping command used on subprocess.call(), by having a value of True or False like in the last “if” statement ?
Here is the code:

import subprocess
from openpyxl import load_workbook
from openpyxl import worksheet
_list_test = []

def ping_rng():
    wb = load_workbook(filename="IP_gav.xlsx")
    ws = wb["172.16.7.X"]
    i = 0

    for IP_ in range(2,258):

        # Get correct cell value
        cell_ = ws.cell(row=IP_, column=1).value
        _list_test.append(cell_)

        # Construct and execute "ping" command
        cmd_param = "-n"
        command = ['ping', cmd_param, '1', str(_list_test[i])]
        response = subprocess.call(command)

        print(response)   # Just to check the value
        
        # Check the "response"
        if response == True:
            print("Is up.")
        elif response == False:
            print("Is down.")
        else: print("Nothing Good")

        i = i + 1

ping_rng()

The code is working as it should, by iterating on a range of IP addresses (which it get from a XLSX file) and by pinging the single IP address like so:

ping 172.16.7.0 -n 1

As a further attempt, I’ve found different posts about verifying if subprocess.check_output() is True or False, but this didn’t worked for me since it returns the string of ping command in “cmd style”, and that is why I’ve opted for subprocess.call() which returns the state of the command.
Tests:
In the code above, I printed the value of “response” variable by using the 2 different methods:

  • With subprocess.call() the return is ‘0’ in any cases (so return False in the last “if” statement)
    or
  • With subprocess.check_output() the return is the ping command itself in “cmd style” (return “Nothing Good” in the last “if” statement)

Advertisement

Answer

ping will exit with 0 as an exit code if it ran successfully. Given that you seem to want to handle error codes in a generic way, you could keep things simple:

import subprocess

def ping_test(ip):
    cmd = ["ping","-n","1",ip]
    response = subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if response == 0:
        print(f"{ip} ping was successful!")
        return
    print(f"{ip} ping was not successful.")

ping_test("127.0.0.1")
ping_test("300.0.0.0")

prints:

#127.0.0.1 ping was successful!
#300.0.0.0 ping was not successful.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement