Check if ping was successful using subprocess in python
Asked Answered
T

4

10

I execute the ping command in python by opening a cmd window with the ping command using python's subprocess module.
For example:

import subprocess
p = subprocess.Popen('ping 127.0.0.1')

Afterwards I check if the output contains "Reply from 'ip':", to see if the ping was successful.
This works in all cases where the cmd is in english.
What can I do to check if a ping was successful on any cmd language?

Timmytimocracy answered 2/3, 2016 at 14:30 Comment(1)
related: Ping a site in Python?Wilbert
C
9

I know this works on Linux, I think it will work also over Windows.

Update: The uncommented code works also in Windows

import subprocess
p = subprocess.Popen('ping 127.0.0.1')
# Linux Version p = subprocess.Popen(['ping','127.0.0.1','-c','1',"-W","2"])
# The -c means that the ping will stop afer 1 package is replied 
# and the -W 2 is the timelimit
p.wait()
print p.poll()

If p.poll() is 0 the ping was succesfull, if it is 1 the destination was unreachable.

A version for many IP addresses will be:

import subprocess
iplist=["127.0.0.1","8.8.8.8"]
for ip in iplist:
    p = subprocess.Popen('ping '+ip,stdout=subprocess.PIPE)
    # the stdout=subprocess.PIPE will hide the output of the ping command
    p.wait()
    if p.poll():
        print ip+" is down"
    else:
        print ip+" is up"
# You end with a log of all the ip addresses
Curd answered 2/3, 2016 at 14:42 Comment(4)
This would work with a simple ping I agree, but what If I have a loop in the batch that pings and returns many results?Timmytimocracy
@Timmytimocracy You want to do the loop in python or in bash?Repeal
in bash, "cmd /C for /l %i in (1, 1, 254) do ping -w 2000 -n 1 195.218.195.%i"Timmytimocracy
this fails for local machinesBickford
H
5

Using python on Linux, I would use check_output()

subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])

this will return true if the ping is successful

Hosea answered 15/1, 2018 at 15:29 Comment(0)
B
1

@elfosardo your solution does not return true if ping is successful. It returns the output of the command or a CalledProcessError exception if the return code was non-zero. Using check_output() as you suggested, here is a possible solution even if not the best one:

import subprocess

def ping():
    try:
        subprocess.check_output(["ping", "-c", "1", "127.0.1.1"])
        return True                      
    except subprocess.CalledProcessError:
        return False
Buddie answered 6/4, 2019 at 12:25 Comment(1)
this doesn't seem to work either for local machinesBickford
T
1

Works on Windows.

For Python 2

import ipaddress, subprocess
myIpAddress = raw_input('Enter an IP Address with a CIDR. >>> ') #192.168.0.1/24
myAdd = ipaddress.ip_interface(unicode(myIpAddress))
myNet = ipaddress.ip_network(myAdd, strict = False) # False lets you enter any ip address in the /24 ip address block.
for i in myNet:
    canPing = subprocess.call('ping /n 2 /w 1000 %s' % str(i))
        if canPing == 0:
            print('I can ping %s' % str(i))
        if canPing == 1:
            print('%s is not responding' % str(i))

For Python 3

import ipaddress, subprocess
myIpAddress = input('Enter an IP Address with a CIDR >>> ') #192.168.0.1/24
myAdd = ipaddress.ip_interface(myIpAddress)
myNet = ipaddress.ip_network(myAdd, strict = False) # False lets you enter any ip address in the /24 ip address block.
for i in myNet:
    canPing = subprocess.call('ping /n 2 /w 1000 %s' % str(i))
        if canPing == 0:
            print('I can ping %s.' % str(i))
        if canPing == 1:
            print('%s is not responding' % str(i))
Tedric answered 3/9, 2020 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.