Monday, August 25, 2008

Ping a range of IP addresses using Python (or whatever else you need to do)

#!/usr/bin/env python
#
# IPRange. Do stuff with IP addresses.
#
# this is code is designed to parse a range of ip addresses and
# do something with them. Example uses are ping, nmap, ssh, etc.
#
# have fun, but don't do illegal things and if it breaks everything
# around you it isn't my fault. Use this only for good, not evil.
#
# contact author(Sam Levine):
# host = darkscyon
# domain = geemail.com (you know, google mail)
# no spam or complaints please. patches are welcome. feedback
# (good or bad) is very welcome.
#
# Be excellent to one another.

def IPRange(octets, func=""):
# octets = "192.168.50-55.1-100"
# func = (some function you've written)
# objects passed to func are strings

if func == "":
def func():
pass

octets = (octets.split('.'))
ranges = []
loop = 0
for octet in octets:
# this is ugly
# basically the idea is that if the user enters a range of ip
# addreses delimited by '-' it parses out the first part of the
# range and the second part.
# it works, just not pretty or readable
if octet.find('-') != -1:
spot = octet.find('-') + 1
octets[loop] = int(octet[:octet.find('-')])
ranges.append(int(octet[spot:]) + 1)
else:
octets[loop] = int(octet)
ranges.append(int(octet) + 1)
loop += 1
CurrentAddress = ""
loop = 0
output = []
for one in range(octets[0], ranges[0]):
for two in range(octets[1], ranges[1]):
for three in range(octets[2], ranges[2]):
for four in range(octets[3], ranges[3]):
for item in (one, two, three, four):
CurrentAddress += str \
((one, two, three, four)[loop]) + "."
loop += 1
CurrentAddress = CurrentAddress[:-1]
output.append(func(CurrentAddress))
CurrentAddress = ""
loop = 0
# return a list of the output
return output

if __name__ == '__main__':
import os
# self test code
def func(x):
print x

test = IPRange("192.168.1-2.10-15", func)
print "The output should be none", test

# example usage
def pinger(x):
input, output = os.popen4('ping -c2 ' + x)
return output
pinglines = IPRange("192.168.1.1-254", pinger)
for streams in pinglines:
for line in streams.readlines():
print line,

1 comment:

Blaze Boy said...

Thanks so much , i was searching for that script for a long time , thanks