Skip to content

Instantly share code, notes, and snippets.

@praveenc
Created April 9, 2020 17:33
Show Gist options
  • Save praveenc/71567c5041d94a926102f90a31040a20 to your computer and use it in GitHub Desktop.
Save praveenc/71567c5041d94a926102f90a31040a20 to your computer and use it in GitHub Desktop.
Extracts IP Ranges from aws ip ranges and writes to file
"""
Extracts IPV4 and IPV6 prefix ranges from ip-ranges.json
REF: https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html#aws-ip-download
Author: Praveen Chamarthi
"""
import requests
import json
aws_ipranges_url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
response = requests.get(aws_ipranges_url, stream=True)
file_name = "ip-ranges.json"
output_filename = "paloalto-ranges"
# download ip-ranges file
with open(file_name, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
# read json to dict
with open(file_name) as f_in:
jsondict = json.load(f_in)
# Extract ip prefixes from Json to a List object
ipv4_prefixes = [ips['ip_prefix'] for ips in jsondict['prefixes']]
ipv6_prefixes = [ips['ipv6_prefix'] for ips in jsondict['ipv6_prefixes']]
# print(ipv4_prefixes)
# print(ipv6_prefixes)
# Write to palo-alto formatted file
output_filename += "-ipv4.txt"
print("Writing ipv4_prefixes to file: {0}".format(output_filename))
with open(output_filename, 'w') as of:
of.writelines(ipv4 + '\n' for ipv4 in ipv4_prefixes)
output_filename = output_filename.replace("ipv4","ipv6")
print("Writing ipv6_prefixes to file: {0}".format(output_filename))
with open(output_filename, 'w') as of:
of.writelines(ipv6 + '\n' for ipv6 in ipv6_prefixes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment