Created
March 15, 2022 03:33
-
-
Save cmlh/6f674ed9bc91741972d7689e2d49efec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" | |
Usage: ip2cidr.py input_file | |
""" | |
import sys, re, netaddr | |
def sanitize (ip): | |
seg = ip.split('.') | |
return '.'.join([ str(int(v)) for v in seg ]) | |
# pointer to input file | |
fp_source = open(sys.argv[1], "r") | |
# pointer to outfile | |
fp_outfile = open('ip.ipset', "w") | |
ptrnSplit = re.compile(' - | , ') | |
# Write ipset header to outfile | |
fp_outfile.write('-N cidr nethash --maxelem 260000\n-N single iphash --maxelem 60000\n',) | |
for line in fp_source: | |
# parse on ' - ' et ' , ' | |
s = re.split(ptrnSplit, line) | |
# sanitize ip: 001.004.000.107 --> 1.4.0.107 to avoid netaddr err. | |
ip = [ sanitize(v) for v in s[:2] ] | |
# conversion ip range to CIDR netblocks | |
# single ip in range | |
if ip[0] == ip[1]: | |
fp_outfile.write('-A single %s\n' % ip[0]) | |
# multiple ip's in range | |
else: | |
ipCidr = netaddr.IPRange(ip[0], ip[1]) | |
for cidr in ipCidr.cidrs(): | |
fp_outfile.write('-A cidr %s\n' % cidr) | |
fp_outfile.write('COMMIT\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment