Last active
May 11, 2016 02:11
-
-
Save princebot/4a7bacf02d76fab7ac8e8bd141d4cc2e to your computer and use it in GitHub Desktop.
This file contains hidden or 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/env python | |
""" | |
Extract and print network addresses from a file. | |
This was written for Python 3.x because Python 2.x is a decade old, and every | |
time you use it, Baby Guido cries. | |
If you have an older python, download the Miniconda Python installer at | |
http://conda.pydata.org/miniconda.html, run it, and load a new shell. | |
If you installed Miniconda for Python 2.x, create a Python 3.x environment: | |
conda create -n py2 python=2 | |
source activate py2 | |
Alternatively, you can just clone github.com/princebot/pythonize and run this: | |
pythonize --miniconda --version 3 | |
Or, if you reaaally want, you can just ask, and I’ll make you a py2 version. ^.^ | |
""" | |
import ipaddress | |
import json | |
import sys | |
def extract_network_objects(text): | |
"""Return a list of network objects from input text.""" | |
try: | |
data = json.loads(text) | |
except json.DecodeError: | |
return None | |
ips = [] | |
for subnet in data['subnets']: | |
address = subnet.get('range_end') | |
mask_bits = subnet.get('mask_bits') | |
network = '{}/{}'.format(address, mask_bits) | |
try: | |
ips.append(ipaddress.ip_network(network, strict=False)) | |
except ValueError: | |
continue | |
return ips or None | |
# extract_network_strings is just an example of how to do this without the | |
# ipaddress library: extract_network_objects is the function that main will | |
# actually use. | |
def extract_network_strings(text): | |
"""Return a list of strings describing networks in CIDR format.""" | |
try: | |
data = json.loads(text) | |
except json.DecodeError: | |
return None | |
ips = [] | |
for subnet in data['subnets']: | |
address = subnet.get('network') | |
mask_bits = subnet.get('mask_bits') | |
ips.append('{}/{}'.format(address, mask_bits)) | |
return ips or None | |
def die(message): | |
"""Print an error message then exit.""" | |
print(message, file=sys.stderr) | |
sys.exit(1) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
die("error: no file argument") | |
input_file = sys.argv[1] | |
try: | |
with open(input_file) as f: | |
file_contents = f.read() | |
except OSError: | |
die("error: cannot read input file {}".format(input_file)) | |
ips = extract_network_objects(file_contents) | |
if ips is None: | |
die("error: no networks found in input file") | |
for ip in ips: | |
print(ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment