Python将IP范围内的IP列表转换为破折号

rlcwz9us  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(133)

给定IP列表

list_of_ips = ['10.0.0.10', '10.0.0.11', '10.0.0.12', '10.0.0.13', '10.0.0.40', '10.0.0.43', '10.0.0.44', '10.0.0.45', '10.0.0.46', '10.0.0.47', '10.0.0.48', '10.0.0.49', '10.0.0.50', '10.0.0.51', '10.0.0.52', '10.0.0.53', '10.0.0.54', '10.0.0.55', '10.0.0.56', '10.0.0.57', '10.0.0.58', '10.0.0.59', '10.0.0.60']

如果IP序列在范围内或单个IP,则要将列表折叠成IP范围内的IP。
示例:

output = ['10.0.0.10-10.0.0.13', '10.0.0.40', '10.0.0.43-10.0.0.60']

下面是部分工作的代码,由于某些原因,我无法获得10.0.0.43 - 10.0.0.60之后的最后一个范围
不知道为什么没有添加

def compare_ips(ip1, ip2):
    last_octet1 = int(ip1.split('.')[-1]) # splits the ip and grabs the last octet
    last_octet2 = int(ip2.split('.')[-1]) # splits the ip and grabs the last octet
    if last_octet1 > last_octet2:
        return -1
    if last_octet1 < last_octet2:
        if (last_octet2 - last_octet1) == 1:
            return 1
        else:
            print("More then 1")
            return 99
    return 0

range, group = [], []
for a, b in zip(list_of_ips, list_of_ips[1:]):
    check = compare_ips(a, b)
    if check == 1:
        group.append(a)
        continue
    elif check == 99:
        if not a in group:
            check2 = compare_ips(a, b)
            if check2 == 1:
                group.append(a)
                continue
            else:
                group.append(a)
        if not b in range:
            range.append(b)
        if len(group) > 1:
            range.append("{}-{}".format(group[0],group[-1]))
            group = []
bgtovc5b

bgtovc5b1#

您可以使用netaddr模块实现此功能:

pip install netaddr

https://netaddr.readthedocs.io/en/latest/tutorial_01.html#list-operations

list_of_ips = ['10.0.0.10', '10.0.0.11', '10.0.0.12', '10.0.0.13', '10.0.0.40', '10.0.0.43', '10.0.0.44', '10.0.0.45', '10.0.0.46', '10.0.0.47', '10.0.0.48', '10.0.0.49', '10.0.0.50', '10.0.0.51', '10.0.0.52', '10.0.0.53', '10.0.0.54', '10.0.0.55', '10.0.0.56', '10.0.0.57', '10.0.0.58', '10.0.0.59', '10.0.0.60']

merged_list = netaddr.cidr_merge(list_of_ips)
print(merged_list)

[IPNetwork('10.0.0.10/31'),
 IPNetwork('10.0.0.12/31'),
 IPNetwork('10.0.0.40/32'),
 IPNetwork('10.0.0.43/32'),
 IPNetwork('10.0.0.44/30'),
 IPNetwork('10.0.0.48/29'),
 IPNetwork('10.0.0.56/30'),
 IPNetwork('10.0.0.60/32')]

现在,如果你想验证你的结果是否正确,你可以这样做:

import ipaddress
[str(ip) for y in merged_list for ip in ipaddress.IPv4Network(y)]

#output
['10.0.0.10',
 '10.0.0.11',
 '10.0.0.12',
 '10.0.0.13',
 '10.0.0.40',
 '10.0.0.43',
 '10.0.0.44',
 '10.0.0.45',
 '10.0.0.46',
 '10.0.0.47',
 '10.0.0.48',
 '10.0.0.49',
 '10.0.0.50',
 '10.0.0.51',
 '10.0.0.52',
 '10.0.0.53',
 '10.0.0.54',
 '10.0.0.55',
 '10.0.0.56',
 '10.0.0.57',
 '10.0.0.58',
 '10.0.0.59',
 '10.0.0.60']

相关问题