Filtering AWS Public IP Addresses in Python

Say what you will about Microsoft at least they make finding the Public IP addresses for their cloud services slightly easier. I recently had to find the External IP Address ranges used for an Amazon AWS Service to allow to add into a firewall rule, this led to a bit of ‘fun with python’ programming and the below script.

Accessing AWS IP Address Ranges

AWS privide their list of IP Addresses as a JSON file type, this is an opensource file type much like XML that can be used to represent data. To access the file navigate to the below URL, this will just display the file and your Internet Browser will just let you view (although doesn’t show in a very handy format).

https://ip-ranges.amazonaws.com/ip-ranges.json

Python Script

Below is the script i created and run on a linux machine i use for my Python programming.

The first part of the script has a command to download the above AWSip-ranges.json file and store in the working folder that this script is located

#!/usr/bin/env python
# Prior to running the below script run the below command to download the ip-ranges.json file from Amazon
#curl https://ip-ranges.amazonaws.com/ip-ranges.json > ip-ranges.json
import json
import os
# Get the absolute path for the directory where this file is located "here"
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "ip-ranges.json")) as file:
json_text = file.read()
json_data = json.loads(json_text)
# Loop through the ip prefixes in the JSON data and print out each
# record.
for prefix in json_data["prefixes"]:
#use the below if statement to filter, below is based on showing all the global cloudfront ip addresses
if prefix["region"] == "GLOBAL" and prefix["service"] == "CLOUDFRONT":
#Use the below to show the prefix info, choose as required
print (prefix["ip_prefix"])
# print (prefix["region"])
# print (prefix["service"])

The middle part of the script reads in the .json file into the json_text and json_data variables then does a for loop and loops through each ip_prefix entry

The bottom half of the script checks each of these ip_prefix entries and uses an if statement to determine what i’m filtering for, this one uses the service of CLOUDFRONT and the region of GLOBAL, these can be changed to match your search criteria.

Below is the URL to my GITHub page and the code for this:

https://github.com/GaryMOnline/AWS-Scripts/blob/master/Get-AWS-IP-Ranges.py

Gary M