def ipv6_addresses(lines): """ Checks if line contains IPv6 Addresses """ # IPv6 - this doesn't handle %interface formats ip6_regex = ("(([0-9a-fA-F]{1,4}:){7,7}([0-9a-fA-F]{1,4})|" "([0-9a-fA-F]{1,4}:){1,7}:|" "([0-9a-fA-F]{1,4}:){1,6}(:[0-9a-fA-F]{1,4})|" "([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" "([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|" "([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" "([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|" "([0-9a-fA-F]{1,4}:){1,1}(:[0-9a-fA-F]{1,4}){1,6}|" ":(:[0-9a-fA-F]{1,4}){1,7})|([0-9a-fA-F]{1,4}:){1,4}:" r"((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3,3}" "(25[0-5]|(2[0-4]|1?[0-9])?[0-9])") ip6_cidr = "(12[0-8]|(1[01]|[0-9])?[0-9])" ip6_match = "^{}(/{})?$".format(ip6_regex, ip6_cidr) ip6_range = r"^{}\s*-\s*{}$".format(ip6_regex, ip6_regex) # Compile regexes increases speed match_ip6_cidr = re.compile(ip6_match) match_ip6_range = re.compile(ip6_range) ip_set = IPSet() remaining = [] for line in lines: line = line.strip() try: if match_ip6_cidr.match(line): logging.info('IPv6 match: %s', line) ip_set.add(line) elif match_ip6_range.match(line): logging.info('IPv6 range: %s', line) start, finish = line.split("-") start = IPAddress(start.strip()) finish = IPAddress(finish.strip()) if start < finish: ip_set.add(IPRange(start, finish)) else: logging.warning( 'IPv4 range: %s (beginning of range ' 'larger than end of range', line) ip_set.add(IPRange(finish, start)) else: logging.info('Unmatched: %s', line) remaining.append(line) except (RuntimeError, TypeError, NameError): logging.debug('Invalid IPv6 addresses: %s', line) remaining.append(line) return ip_set, remaining
def ipv4_addresses(lines): """ Checks if line contains IPv4 Addresses """ # IPv4 - this doesn't handle %interface formats ip4_regex = (r"((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3,3}" "(25[0-5]|(2[0-4]|1?[0-9])?[0-9])") ip4_cidr = "(3[0-2]|[12]?[0-9])" ip4_match = "^{}(/{})?$".format(ip4_regex, ip4_cidr) ip4_range = r"^{}\s*-\s*{}$".format(ip4_regex, ip4_regex) # Compile regexes increases speed match_ip4_cidr = re.compile(ip4_match) match_ip4_range = re.compile(ip4_range) ip_set = IPSet() remaining = [] for line in lines: line = line.strip() try: if match_ip4_cidr.match(line): logging.info('IPv4 match: %s', line) ip_set.add(line) elif match_ip4_range.match(line): logging.info('IPv4 range: %s', line) start, finish = line.split("-") start = IPAddress(start.strip()) finish = IPAddress(finish.strip()) if start < finish: ip_set.add(IPRange(start, finish)) else: logging.warning( 'IPv4 range: %s (beginning of range ' 'larger than end of range', line) ip_set.add(IPRange(finish, start)) else: remaining.append(line) except (RuntimeError, TypeError, NameError): logging.debug('Invalid IPv4 addresses: %s', line) remaining.append(line) return ip_set, remaining