Reputation: 27
I want to ping a range of IP addresses in Python and print either: "The IP is reachable with a X% percent package loss" or "The IP isn't reachable with a X% package loss"
The range I want to try is 192.168.0.X with X being the range of 0-255
Here is my code so far;
import shlex
import subprocess
import os
for x in range(0, 256):
cmd=shlex.split("ping -cl 192.168.0." + str(x))
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError,e:
#Will print the command failed with its exit status
print "The IP {0} isn't reachable".format(cmd[-1])
else:
print "The IP {0} is reachable".format(cmd[-1])
what is wrong with my code? also I noticed when I try the command "ping -cl 192.168.0.2" it says that -cl is an administrator only command. I am an admin on my computer and I ran cmd as admin so whats wrong with that?
I am using Windows 8.1 Python v2.7.9
Upvotes: 2
Views: 3353
Reputation: 3515
If you have scapy module installed you should try using :
clients = arping("192.168.1.*")
print clients
It is fast and will also print the mac adress associated with the ip so it is quite helpful.
Upvotes: 0
Reputation: 180391
If you are using linux and you just want to see the packet loss:
import shlex
from subprocess import PIPE, Popen
cmd1 = shlex.split("grep -oP '\d+(?=% packet loss)'")
for x in range(1, 256):
cmd = "ping -c 4 192.168.43.{}".format(x).split()
p1 = Popen(cmd, stdout=PIPE, stderr=PIPE)
p2 = Popen(cmd1, stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0].rstrip()
if output == "100":
print("{}% percent packet loss from unreachable ip {}".format(output, cmd[-1]))
else:
print("{}% percent packet loss from reachable ip {}".format(output, cmd[-1]))
Disclaimer I don't use windows so am open to correction but this may work:
for x in range(1, 256):
cmd = "ping -c 1 192.168.43.{}".format(x).split()
p1 = Popen(cmd, stdout=PIPE, stderr=PIPE)
lines = p1.communicate()[0].splitlines()
output = (lines[-2]).rsplit(None,5)
output = output[-5].rstrip()
if output == "100%":
print("{} percent packet loss from unreachable ip {}".format(output, cmd[-1]))
else:
print("{} percent packet loss from reachable ip {}".format(output, cmd[-1]))
Upvotes: 1