Skip to content

Instantly share code, notes, and snippets.

@kranzrm
Created August 31, 2017 19:30
Show Gist options
  • Save kranzrm/86fe47ac12869fd1f35537ac788b6213 to your computer and use it in GitHub Desktop.
Save kranzrm/86fe47ac12869fd1f35537ac788b6213 to your computer and use it in GitHub Desktop.
CIDR list dedup and hierarchy tree
#!/usr/bin/python
from netaddr import *
import pprint
import itertools
pp = pprint.PrettyPrinter(indent=4)
def get_cidr_list(filename):
#file must have one cidr per line
#192.168.0.0/16
#192.168.0.0/24
#TODO handle blank lines
with open(filename) as f:
content = f.readlines()
content = [x.strip() for x in content]
cidr_list = []
for line in content:
net = IPNetwork(line)
cidr_list.append(net)
return cidr_list
def cidr_fit(cidr_one, cidr_two):
#Check to see if cidr_two fits into cidr_one
if ((cidr_two.first >= cidr_one.first) and (cidr_two.last <= cidr_one.last)):
#cidr_two fits inside cidr_one
return True
else:
return False
def is_root(net, net_list):
parents = 0
for net2 in net_list:
if ((cidr_fit(net2,net)) and (net != net2)):
#use dict to dedup and count parents
parents += 1
if parents == 0:
return True
return False
def get_children(parent,net_list):
children = []
for n in net_list:
if ((cidr_fit(parent,n)) and (parent != n)):
children.append(n)
return children
def build_tree(net_list):
tree = {}
root_list=[]
for net in net_list:
if is_root(net,net_list):
root_list.append(net)
for net in root_list:
children = get_children(net,net_list)
tree[net]=build_tree(children)
return tree
def pprint_cidr(tree,indent=0):
for net in tree.keys():
print "{}{}".format(" " * indent,str(net))
pprint_cidr(tree[net], indent+1)
def print_root(tree):
for net in tree.keys():
print str(net)
if __name__ == "__main__":
#Optimization Example:
cidr_list = get_cidr_list('cidrs_in file.txt')
tree = build_tree(cidr_list)
print("##############################")
print("# Optimized Networks")
print("##############################")
print_root(tree)
print("##############################")
print("# Network Tree")
print("##############################")
pprint_cidr(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment