1

I am trying to get a list of IP addresses if they match a subnet via Python 2.7 and netaddr module.

I am currently running this on my Windows PC with Python 2.7 installed from the www.python.org site.

I intend to run it on RHEL 6.x with python 2.7 installed.

This should take the IP address from ip_list and compare it to the banned_subnets if it finds a match then it should add these to new_list and print out Match found.

There should be two matches

10.11.117.137 is in subnet 10.11.117.0/24
10.24.33.21 is in subnet 10.24.33.0/24

I can't fathom out checking multiple values in a list against a list with multiple values.

I have read the docs on netaddr, I have read the Python - Comparing two lists on this site and several others but I am just not getting it.

Here is the bit of code I am trying to get to work

import netaddr

# Range of IP Addresses that we see connections from.
ip_list = ['10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22']

# List of IP Subnets that members of IP list should not be from.
banned_subnets = ['10.11.117.0/24', '10.24.33.0/24']

# Using banned_subnets as our master list see if any of the ip_list addresses are present
# If they are present print the ip address

new_list = []

for Z in banned_subnets:
    for X in ip_list:
        if netaddr.IPAddress(X) == netaddr.IPNetwork(Z):
            new_list.append(X)
            print 'Match Found'
        else:
            print 'No Matches Found'

print new_list

When I run this i get the following returned

E:\Python27\python.exe E:/Users/twelsh/PycharmProjects/lool/liist-loop.py
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
['10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22', '10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22']

Process finished with exit code 0

I'm new to all this Python malarky. All advice would be appreciated.

Community
  • 1
  • 1
twelsh37
  • 189
  • 3
  • 13

1 Answers1

1

Use set intersection with & operator and save result to list.

new_list = [str(ip) for ip in netaddr.IPSet(ip_list) & (netaddr.IPSet(banned_subnets))]
print new_list
P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
  • Thanks. This seems to work although it returns 3510 'No Matches Found' from a list of 90 IP Addresses in the 'ip_list' and 39 subnets in the 'banned_subnets' Is there a more efficient way of doing this loop as it burns time looping over all addresses for every banned subnet? – twelsh37 Mar 16 '14 at 16:45
  • Edited answer with more efficient algorithm. – P̲̳x͓L̳ Mar 16 '14 at 19:37