Skip to content

Instantly share code, notes, and snippets.

@richardcurteis
Last active July 19, 2021 23:52
Show Gist options
  • Save richardcurteis/b47409b8871c14dac6fd6cc872929c07 to your computer and use it in GitHub Desktop.
Save richardcurteis/b47409b8871c14dac6fd6cc872929c07 to your computer and use it in GitHub Desktop.
Parse input file of IP addresses and print all plain addresses and all possible addresses with CIDR notation ranges
#!/usr/bin/python3
import ipaddress
import sys
import re
VALID_HOSTS = []
INFILE = []
def enum_cidr(host):
return [str(ip) for ip in ipaddress.IPv4Network(host)]
def evaluate_cidr(cidr):
ip_list = enum_cidr(cidr)
if len(ip_list) > 0:
for ip in ip_list:
if is_ip(ip):
print(ip)
def parse_input():
for ip in INFILE:
if "/" in ip:
evaluate_cidr(ip)
else:
if is_ip(ip):
print(ip)
def is_ip(ip):
pattern = r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"
return True if(re.match(pattern, ip) and valid_host(ip)) else False
def valid_host(ip):
for host in VALID_HOSTS:
if host in ip:
return True
return False
def populate_array(infile):
pattern = r"(?:[0-9]{1,3}\.){3}"
with open(infile, 'r') as file:
for line in file:
if line is not None:
line = line.rstrip()
VALID_HOSTS.append(re.search(pattern, line).group(0))
INFILE.append(line)
if __name__ == "__main__":
if len(sys.argv) != 1:
populate_array(sys.argv[1])
VALID_HOSTS = list(set(VALID_HOSTS))
parse_input()
else:
print("[!] Supply input file")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment