Last active
February 12, 2017 20:55
-
-
Save VGostyuzhov/9d2d383465567accef5218edd58f5899 to your computer and use it in GitHub Desktop.
Reads file with networks(CIDR or range format) and generates list of IP addresses, contained in this networks.
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
import ipaddress | |
import re | |
firstIP_pattern = re.compile('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)') | |
lastIP_pattern = re.compile('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$') | |
CIDR_pattern = re.compile('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$') | |
with open('networks.txt', 'r') as file, open('ip_list.txt', 'w+') as result_file: | |
for line in file: | |
print line | |
line = line.strip('\n') | |
line = line.strip() | |
if not firstIP_pattern.match(line): | |
continue | |
if CIDR_pattern.match(line): | |
cidr_net = ipaddress.ip_network(unicode(line, 'utf-8')) | |
for ip in cidr_net: | |
result_file.write(str(ip) + '\n') | |
else: | |
first_IPv4 = ipaddress.IPv4Address(unicode(firstIP_pattern.search(line).group(0), 'utf-8')) | |
last_IPv4 = ipaddress.IPv4Address(unicode(lastIP_pattern.search(line).group(0), 'utf-8')) | |
for net in ipaddress.summarize_address_range(first_IPv4, last_IPv4): | |
for ip in net: | |
result_file.write(str(ip) + '\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment