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.