Networking - Multiple Ping Script in Python - Stack Overflow

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

12/27/2018 networking - Multiple ping script in Python - Stack Overflow

Multiple ping script in Python Ask Question

I'm unable to find any good easy to


learn documentation on python and
18 networking. In this instance, I'm just
trying to make a easy script which I
can ping a number of remote
machines.

14 for ping in range(1,10):


ip="127.0.0."+str(ping)
os.system("ping -c 3 %s" % ip)

A simple script like that will ping the


machines fine, but I'd like to get the
script to returns 'active' 'no response'
Which makes me think I'll have to
look up the time module as well, I
think time.sleep(5) and after that,
there would be a break statement.
Which makes me think there should
be a while loop inside for. I'm not
100% sure, I could be going in the
wrong direction completely :/ if
anyone could help or point me in the
direction of some documentation
that'd be great.

python networking ping

edited Aug 24 '12 at 4:36


Santosh Kumar
10.3k 14 43 93

asked Aug 23 '12 at 23:09


kuiper
93 1 1 3

I'm not sure why you think you need


the time module? I'd suggest
researching how to parse the
STDOUT from a subprocess (which is
what you should be using instead of
os.system() ) – ernie Aug 23 '12 at
23:13

2 you
By using our site, Tryacknowledge
Scapy. – kichik
thatAug
you23 '12 at
have read and understand our Cookie Policy, Privacy Policy, and our
23:15
Terms of Service.
Here is an example
https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 1/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow
github.com/lbaby/javalearn/blob/maste
r/shell/ppe.py – lbaby Feb 13 '13 at
12:50

No do not use scapy, scapy is terrible


for anything requiring either
throughput or reliability... Both are
required for monitoring applications. –
Mike Pennington Jan 27 '15 at 18:27

8 Answers

Try subprocess.call . It saves the


return value of the program that was
25 used.

According to my ping manual, it


returns 0 on success, 2 when pings
were sent but no reply was received
and any other value indicates an
error.

# typo error in import


import subprocess

for ping in range(1,10):


address = "127.0.0." + str(ping)
res = subprocess.call(['ping', '-c
if res == 0:
print "ping to", address, "OK"
elif res == 2:
print "no response from", addr
else:
print "ping to", address, "fai

edited Jan 6 '15 at 5:21


Snehal Parmar
2,861 1 21 35

answered Aug 23 '12 at 23:21


Roland Smith
25.9k 3 29 54

wow.... thanks guys, i really do


appreciate all of your help. peace :) –
kuiper Aug 26 '12 at 12:37

3 You'rw welcome. Remember to mark


answers that helped you as accepted
(click the green tickmark below the
question vote tally), it signals to other
visitors the answer was helpful. :-) –
Roland Smith Aug 28 '12 at 8:21

1 subprocess.call() pings only one


ip at a time. To ping multiple ips
simultaneously subprocess.Popen()
could be used – jfs Apr 14 '14 at 17:16
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
Terms of Service.

https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 2/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow

This script:

import subprocess
9 import os
with open(os.devnull, "wb") as limbo:
for n in xrange(1, 10):
ip="192.168.0.{0}".for
result=subprocess.Pope
stdout=limbo,
if result:
print ip, "ina
else:
print ip, "act

will produce something like this


output:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

You can capture the output if you


replace limbo with subprocess.PIPE
and use communicate() on the Popen
object:

p=Popen( ... )
output=p.communicate()
result=p.wait()

This way you get the return value of


the command and can capture the
text. Following the manual this is the
preferred way to operate a
subprocess if you need flexibility:

The underlying process creation


and management in this module is
handled by the Popen class. It
offers a lot of flexibility so that
developers are able to handle the
less common cases not covered
by the convenience functions.

edited Jan 3 '13 at 11:34

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
answered Aug 23 '12 at 23:15
Terms of Service.
hochl

https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 3/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow
8,929 7 33 67

Please leave a comment with an


explanation why you voted down, so
the answer can be improved. – hochl
Mar 14 '17 at 8:15

Thank you so much for this. I have


modified it to work with Windows. I
5 have also put a low timeout so, the
IP's that have no return will not sit
and wait for 5 seconds each. This is
from hochl source code.

import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(200, 240):
ip="10.2.7.{0}".format
result=subprocess.Pope
stdout=limbo,
if result:
print ip, "ina
else:
print ip, "act

Just change the ip= for your scheme


and the xrange for the hosts.

answered Sep 23 '13 at 20:27


Robert N
51 1 2

I'm a beginner and wrote a script to


ping multiple hosts.To ping multiple
3 host you can use ipaddress module.

import ipaddress
from subprocess import Popen, PIPE

net4 = ipaddress.ip_network('192.168.2
for x in net4.hosts():
x = str(x)
hostup = Popen(["ping", "-c1", x],
output = hostup.communicate()[0]
val1 = hostup.returncode
if val1 == 0:
print(x, "is pinging")
else:
print(x, "is not responding")

answered Jan 16 '16 at 16:53


Sumit
31 1

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
Terms of Service.

https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 4/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow

To ping several hosts at once you


could use subprocess.Popen() :
1
#!/usr/bin/env python3
import os
import time
from subprocess import Popen, DEVNULL

p = {} # ip -> process
for n in range(1, 100): # start ping p
ip = "127.0.0.%d" % n
p[ip] = Popen(['ping', '-n', '-w5'
#NOTE: you could set stderr=subpro

while p:
for ip, proc in p.items():
if proc.poll() is not None: #
del p[ip] # remove from th
if proc.returncode == 0:
print('%s active' % ip
elif proc.returncode == 1:
print('%s no response'
else:
print('%s error' % ip)
break

If you can run as a root you could use


a pure Python ping script or scapy :

from scapy.all import sr, ICMP, IP, L3

conf.L3socket = L3RawSocket # for loop


ans, unans = sr(IP(dst="127.0.0.1-99")
ans.summary(lambda (s,r): r.sprintf("%

edited May 23 '17 at 12:34


Community ♦
1 1

answered Aug 24 '12 at 1:11


jfs
261k 77 547 1075

import subprocess
import os
'''
0 servers.txt contains ip address in fol
192.168.1.1
192.168.1.2
'''
with open('servers.txt', 'r') as f
for ip in f:
result=subprocess.Popen(["
stderr=f).wait()
if result:
print(ip, "inactive")
else:
print(ip, "active")

edited Jan 12 '16 at 8:01


Nehal
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
1,358 4 14 30
Terms of Service.

d J 12 '16 t 7 29
https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 5/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow
answered Jan 12 '16 at 7:29
Razi Ahmed
1

Python actually has a really sweet


method that will 'return an iterator
0 over the usable hosts in the network'.
(setting strict to false iterates over all
IPs)

For example:

import subprocess
import ipaddress

subnet = ipaddress.ip_network('192.168
for i in subnet.hosts():
i = str(i)
subprocess.call(["ping", "-c1", "-

The wait interval (-i0.1) may be


important for automations, even a
one second timeout (-t1) can take
forever over a .0/24

EDIT: So, in order to track ICMP


(ping) requests, we can do something
like this:

#!/usr/bin/env python

import subprocess
import ipaddress

alive = []
subnet = ipaddress.ip_network('192.168
for i in subnet.hosts():
i = str(i)
retval = subprocess.call(["ping",
if retval == 0:
alive.append(i)
for ip in alive:
print(ip + " is alive")

Which will return something like:

192.168.0.1 is alive
192.168.0.2 is alive
192.168.1.1 is alive
192.168.1.246 is alive

i.e. all of the IPs responding to ICMP


ranging over an entire /23-- Pretty
cool!

edited May 22 '16 at 6:45

By using our site, you acknowledge that22


answered May you
'16have read and understand our Cookie Policy, Privacy Policy, and our
at 5:27
Terms of Service. andylukem

https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 6/7
12/27/2018 networking - Multiple ping script in Python - Stack Overflow
51 5

FYI, I threw errors on this until


specifying the IP address as being
unicode: subnet =
ipaddress.ip_network(u'192.168.1.0/2
3', strict=False) – blackappy Jan 2 at
22:02

import subprocess,os,threading,time
from queue import Queue
lock=threading.Lock()
-1 _start=time.time()
def check(n):
with open(os.devnull, "wb") as lim
ip="192.168.21.{0}".fo
result=subprocess.Pope
ip],stdout=limbo, stderr=limbo).wait()
with lock:
if not result:
print (ip, "ac
else:
pass

def threader():
while True:
worker=q.get()
check(worker)
q.task_done()
q=Queue()

for x in range(255):
t=threading.Thread(target=threader
t.daemon=True
t.start()
for worker in range(1,255):
q.put(worker)
q.join()
print("Process completed in: ",time.ti

I think this will be better one.

answered Apr 2 '16 at 23:56


Avijit Naskar
3 3

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
Terms of Service.

https://stackoverflow.com/questions/12101239/multiple-ping-script-in-python 7/7

You might also like