给定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 = []
1条答案
按热度按时间bgtovc5b1#
您可以使用
netaddr
模块实现此功能:https://netaddr.readthedocs.io/en/latest/tutorial_01.html#list-operations
现在,如果你想验证你的结果是否正确,你可以这样做: