[Tutor] searching for an ip and subnets in a dir of csv's

Wayne srilyk at gmail.com
Wed Jul 29 15:05:58 CEST 2009

On Wed, Jul 29, 2009 at 7:43 AM, Nick Burgess <burgess.nick at gmail.com>wrote:

>  And you were looking for, do you want it to return nothing? Or
> both and Or only as it's the closest
> match?
> I would like it to return both, all possible matches.
> The data looks something like this in the CSV's,
> Server                 foo.bar.org        such&such org
> Apache farm subnet            so&so corp.
> the format is random
> The script will be ran from a third party tool so only one argument
> can be passed to it which will be an entire IP address.  If within the
> CSV's there is no 32 bit match there could be a subnet that might
> match, thats why I need it to loop over the dots.  If there is a 32
> bit and a subnet match both will be returned which is desirable .


That will give you the regex for matching any IP addresses. If you use the
findall method

then it will give you a list of IPs (as strings).
If you packed each of these IPs into a dictionary you could use this to get
the key:

for ip in iplist:
    key = ip[:ip.rfind('.')]  # Gets everything but the last bit
    if mydict.get(key):
        mydict[key] = [ip]

Then you just have to do something like

Which will return None or the list of IPs.

Although now that I'm thinking a little more about it, that's probably
excessive for your needs - you can just do this:

matches = []
ipnet = sys.argv[1][:sys.argv[1].rfind('.')]

for ip in iplist:
    if ip.startswith(ipnet):

and that should give you a list of all IPs within that same subnet.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090729/86f4208c/attachment.htm>

More information about the Tutor mailing list