Skip to content

Instantly share code, notes, and snippets.

@goncalor
Created May 16, 2022 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goncalor/f13a78aea82d828f5d40b1f70d3b071e to your computer and use it in GitHub Desktop.
Save goncalor/f13a78aea82d828f5d40b1f70d3b071e to your computer and use it in GitHub Desktop.
Collapses subnets and/or IPs into the smallest possible set of subnets
#!/usr/bin/env python3
# Collapses subnets and/or IPs into the smallest possible set of subnets
import sys
import ipaddress
if len(sys.argv) != 2:
print("Usage: {} <file>".format(sys.argv[0]))
sys.exit(-1)
with open(sys.argv[1]) as f:
nets = set()
for line in f.readlines():
line = line.strip()
nets.add(ipaddress.ip_network(line))
collapsed = list(ipaddress.collapse_addresses(nets))
for subnet in collapsed:
print(subnet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment