How do I convert a list of IP addresses to a list of CIDRs? Google's ipaddr-py library has a method called summarize_address_range(first, last) that converts two IP addresses (start & finish) to a CIDR list. However, it cannot handle a list of IP addresses.
Example:
>>> list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
>>> convert_to_cidr(list_of_ips)
['10.0.0.0/30','10.0.0.5/32']
You can do it in one line using netaddr:
Well,
summarize_address_range
reduces your problem to splitting your list into consecutive ranges. Given that you can convert IP addresses to integers usingthis should not be too hard.
For the comment made by CaTalyst.X, note that you need to change to code in order for it to work.
This:
Needs to become this:
If you use the first instance of the code, you'll get an exception since ip_range_to_cidrs isn't a valid attribute to the netaddr method.
Install netaddr.
Use functions of netaddr:
Expand CIDR ranges into full IP lists, by taking an input file of ranges and utilizing netaddr https://github.com/JeremyNGalloway/cidrExpand/blob/master/cidrExpand.py
in python3, we have a buildin module for this: ipaddress.