List of IP addresses in Python to a list of CIDR

妖精的绣舞 提交于 2019-12-12 07:16:25

问题


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']

回答1:


You can do it in one line using netaddr:

cidrs = netaddr.iprange_to_cidrs(ip_start, ip_end)



回答2:


Install netaddr.

pip install netaddr

Use functions of netaddr:

# Generate lists of IP addresses in range.
ip_range = netaddr.iter_iprange(ip_start, ip_end)
# Convert start & finish range to CIDR.
ip_range = netaddr.cidr_merge(ip_range)



回答3:


in python3, we have a buildin module for this: ipaddress.

list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
import ipaddress
nets = [ipaddress.ip_network(_ip) for _ip in list_of_ips]
cidrs = ipaddress.collapse_addresses(nets)
list(cidrs)
Out[6]: [IPv4Network('10.0.0.0/30'), IPv4Network('10.0.0.5/32')]



回答4:


Well, summarize_address_range reduces your problem to splitting your list into consecutive ranges. Given that you can convert IP addresses to integers using

def to_int(str): struct.unpack("!i",socket.inet_aton(str))[0]

this should not be too hard.




回答5:


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

from netaddr import IPNetwork
import sys

if len(sys.argv) < 2:
    print 'example usage: python cidrExpand.py cidrRanges.txt >> output.txt'

with open(sys.argv[1], 'r') as cidrRanges:
    for line in cidrRanges:
        ip = IPNetwork(line)
        for ip in ip:
            print ip

cidrRanges.close()
exit()



回答6:


For the comment made by CaTalyst.X, note that you need to change to code in order for it to work.

This:

cidrs = netaddr.ip_range_to_cidrs('54.64.0.0', '54.71.255.255')

Needs to become this:

cidrs = netaddr.iprange_to_cidrs('54.64.0.0', '54.71.255.255')

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.



来源:https://stackoverflow.com/questions/6708272/list-of-ip-addresses-in-python-to-a-list-of-cidr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!