[英]List of IP addresses in Python to a list of CIDR
How do I convert a list of IP addresses to a list of CIDRs?如何将 IP 地址列表转换为 CIDR 列表? 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.
Google 的 ipaddr-py 库有一个名为 summarise_address_range(first, last) 的方法,它将两个 IP 地址(开始和结束)转换为 CIDR 列表。 However, it cannot handle a list of IP addresses.
但是,它无法处理 IP 地址列表。
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']
Install netaddr.安装网络地址。
pip install netaddr
pip 安装 netaddr
Use functions of netaddr: 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)
in python3, we have a buildin module for this: ipaddress.在 python3 中,我们有一个内置模块: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')]
You can do it in one line using netaddr:您可以使用 netaddr 在一行中完成:
cidrs = netaddr.iprange_to_cidrs(ip_start, ip_end)
Well, summarize_address_range
reduces your problem to splitting your list into consecutive ranges.好吧,
summarize_address_range
将您的问题减少到将列表拆分为连续范围。 Given that you can convert IP addresses to integers using鉴于您可以使用 IP 地址转换为整数
def to_int(str): struct.unpack("!i",socket.inet_aton(str))[0]
this 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.对于 CaTalyst.X 的评论,请注意您需要更改代码才能使其正常工作。
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.如果您使用代码的第一个实例,您将收到异常,因为 ip_range_to_cidrs 不是 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通过获取范围的输入文件并利用 netaddr https://github.com/JeremyNGalloway/cidrExpand/blob/master/cidrExpand.py ,将 CIDR 范围扩展为完整的 IP 列表
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()
5 minutes solution 5分钟解决方案
Thank me later:-P稍后谢谢我:-P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.