-1

Can I pass file in "ip_list" and "banned_subnets". I have multiple list of IP's which need to be get match with multiple subnets, and it is not possible to list them all in script. For that I have created two files ipaddr_list which has list of IP's and sub_list which has list of subnets.

Can some suggest how do I get this in below script:

import netaddr

ip_list = ['10.22.140.10', '10.11.14.11', '10.71.13.13', '10.10.131.2', '10.12.6.11', '10.1.6.10']

banned_subnets = ['10.1.6.0/24', '10.10.13.0/24', '10.10.14.0/24' ]

new_list = [str(ip) for ip in netaddr.IPSet(ip_list) & (netaddr.IPSet(banned_subnets))]

print new_list
beginnertopython
  • 101
  • 3
  • 10

1 Answers1

2

I'm supposing that files you're saying you have for ip_list and banned_subnets are text files with each line containing an IP.

What you need to do is read those text file and strip them so they take form of list. I will add the code for one below you can accordingly use the code for another one.

with open('ip_list.txt') as f:
    IP_list = [line for line in f]

Hope you can do the same for banned_subnets as well.

harshil9968
  • 3,254
  • 1
  • 16
  • 26
  • It works but getting below error: ['10.11.10.100\n', '10.11.18.110\n', '10.71.131.123\n', '10.71.131.200\n', '10.11.6.11\n', '10.11.6.121\n', '10.11.6.11\n', '204.11.6.11\n', '\n'] ['10.11.6.0/24\n', '10.71.131.0/24\n', '10.11.18.0/24_\n'] Below is the modified script: #!/usr/bin/python import netaddr with open('ip_list.txt') as f: ip_list = [line for line in f] with open('sub.txt') as p: banned_subnets = [line for line in p] new_list = [str(ip) for ip in netaddr.IPSet(ip_list) & (netaddr.IPSet(banned_subnets))] print new_list – beginnertopython May 10 '16 at 12:17
  • So you can use this to form list: `f = open('ip_list.txt' ,'r') IP_list = (f.read()).split('\n')` – harshil9968 May 10 '16 at 12:32
  • [Read this](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python) here how to read line by line to list is given – harshil9968 May 10 '16 at 12:36
  • This works for me. Is it possible to print unmatched ip's means can i print ip which is out of my subnet. – beginnertopython May 11 '16 at 06:18
  • With this i may getting exact matches. can some one help me to get ip's in output which is not in listed subnets. I want to find ip's which is not in my subnet. – beginnertopython May 11 '16 at 07:38