Skip to content

Instantly share code, notes, and snippets.

@shibeta
Created August 23, 2024 03:40
Show Gist options
  • Save shibeta/2248c06a56ab28dd1533e5bfaed8eadb to your computer and use it in GitHub Desktop.
Save shibeta/2248c06a56ab28dd1533e5bfaed8eadb to your computer and use it in GitHub Desktop.
Convert ip range to ipcidr
'''
Convert
192.168.0.0-192.168.2.255
to
"192.168.0.0/23",
"192.168.2.0/24",
'''
import ipaddress
def ip_range_to_cidrs(start_ip:str, end_ip:str):
try:
start = ipaddress.ip_address(start_ip)
end = ipaddress.ip_address(end_ip)
return [str(cidr) for cidr in ipaddress.summarize_address_range(start, end)]
except ValueError:
return []
def process_ip_line(line:str):
line = line.strip()
if '-' in line:
start, end = line.split('-')
cidrs = ip_range_to_cidrs(start.strip(), end.strip())
return cidrs, []
else:
try:
ip = ipaddress.ip_address(line)
return [], [str(ip)]
except ValueError:
return [], []
def categorize_ip(ip_str:str):
ip = ipaddress.ip_address(ip_str)
return 'ipv4' if ip.version == 4 else 'ipv6'
def categorize_cidr(cidr_str:str):
network = ipaddress.ip_network(cidr_str)
return 'ipv4_cidr' if network.version == 4 else 'ipv6_cidr'
def main(input_file:str, output_file:str):
ipv4 = set()
ipv4_cidr = set()
ipv6 = set()
ipv6_cidr = set()
with open(input_file, 'r') as infile:
for line in infile:
new_cidrs, new_ips = process_ip_line(line)
for cidr in new_cidrs:
if categorize_cidr(cidr) == 'ipv4_cidr':
ipv4_cidr.add(cidr)
else:
ipv6_cidr.add(cidr)
for ip in new_ips:
if categorize_ip(ip) == 'ipv4':
ipv4.add(ip)
else:
ipv6.add(ip)
if not new_cidrs and not new_ips:
print(f"Error processing line: {line.strip()}")
with open(output_file, 'w') as outfile:
# Write IPv4 addresses
for ip in sorted(ipv4, key=ipaddress.IPv4Address):
outfile.write(f'"{ip}",\n')
# Write IPv4 CIDR
for cidr in sorted(ipv4_cidr, key=ipaddress.IPv4Network):
outfile.write(f'"{cidr}",\n')
# Write IPv6 addresses
for ip in sorted(ipv6, key=ipaddress.IPv6Address):
outfile.write(f'"{ip}",\n')
# Write IPv6 CIDR
for cidr in sorted(ipv6_cidr, key=ipaddress.IPv6Network):
outfile.write(f'"{cidr}",\n')
if __name__ == "__main__":
input_file = "input.txt"
output_file = "output.txt"
main(input_file, output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment