Skip to content

Instantly share code, notes, and snippets.

@ddfault
Forked from toringe/cidr.py
Last active July 31, 2021 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddfault/a11d537e13f0447c3585e18b1ba4e63b to your computer and use it in GitHub Desktop.
Save ddfault/a11d537e13f0447c3585e18b1ba4e63b to your computer and use it in GitHub Desktop.
Merge CIDR blocks into super blocks if possible
#!/usr/bin/env python
#
# Example 1: All blocks in list.txt, one CIDR per line
# cat list.txt | cidr.py (linux)
# type list.txt | cidr.py (Windows)
#
# Example 2: Echo CIDR blocks to stdout
# echo 1.2.3.0/25 1.2.3.128/25 | cidr.py
# Adjusted python print to print() to work with my python 3.5 on Windows.
# Added routine so I could feed it multiple input text files as arguments to merge
# Usage cidr.py Input1.txt Input2.txt ... InputN.txt > OutputMerged.txt
# Example 3: Read CIDR blocks from txt files and output to a txt file
# cidr.py list1.txt list2.txt list3.txt > outputList.txt
import sys
from netaddr import *
import os
#If argument list is more than just pythone file assume reading from files and not stdin
if(len(sys.argv) > 1):
# Save Argument List to file to get rid of pythone file
ArgumentsList = sys.argv
ArgumentsList.pop(0)
# Setup empty list for looping through argument files
InputDataList = []
# Loop through all argument files and append to list
for x in ArgumentsList:
with open(x,'r') as f:
InputDataList.extend(f.readlines())
else :
# Read from stdin
InputDataList = sys.stdin.readlines()
if len(InputDataList) == 1:
# Input from echo
InputDataList = InputDataList[0].split()
# Create an IPSet of the CIDR blocks
# IPSet automatically runs cidr_merge
nets = IPSet(InputDataList)
# Output the superset of CIDR blocks
for cidr in nets.iter_cidrs():
print (cidr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment