Skip to content

Instantly share code, notes, and snippets.

@djenriquez
Last active July 10, 2018 21:00
Show Gist options
  • Save djenriquez/4ab8285753854c1272fa5e1ad8eb3cb7 to your computer and use it in GitHub Desktop.
Save djenriquez/4ab8285753854c1272fa5e1ad8eb3cb7 to your computer and use it in GitHub Desktop.
Find AWS public IP ranges by region
#!/usr/local/bin/python3
import argparse
import json
import requests
"""
IPRangeFinder will fetch the ip-ranges file from AWS
and parse it to find the public IP addresses registered
to a region. This is useful when searching for the range
of public IP addresses that can be allocated to your AWS
EC2 infrastructure.
Use: python3 find_aws_public_ip_ranges_by_region.py --region us-east-1
"""
class IPRangeFinder:
def __init__(self):
pass
def start(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('-i', '--ip-ranges-endpoint', dest='ip_ranges', default='https://ip-ranges.amazonaws.com/ip-ranges.json', help='The URl to the ip-ranges.json file')
self.parser.add_argument('-r', '--region', dest='region', required=True, help='The region to find IP addresses for')
self.parser.add_argument('--use-file', dest='use_file', action='store_true', help='Specified if a flat file should be used instead of the endpoint')
self.parser.add_argument('-f', '--file', dest='ip_file', help='The location of the file to parse')
self.parser.add_argument('--ipv6', dest='ipv6', action='store_true', help='Find ipv6 ranges')
self.args = self.parser.parse_args()
if self.args.use_file:
if(self.args.ip_file):
self.__import_ip_ranges_file()
else:
print('Specify an "ip-ranges.json" file to import with "--file"')
return
else:
self.__fetch_ip_ranges()
self.__filter_ip_ranges_by_region()
def __fetch_ip_ranges(self):
request_url = self.args.ip_ranges
r = requests.get(request_url)
self.ip_ranges = r.json()
def __import_ip_ranges_file(self):
with open(self.args.ip_file, 'r') as f:
ip_ranges_raw = f.read()
self.ip_ranges = json.loads(ip_ranges_raw)
def __filter_ip_ranges_by_region(self):
array = 'prefixes'
field = 'ip_prefix'
if self.args.ipv6:
array = 'ipv6_prefixes'
field = 'ipv6_prefix'
for prefix in self.ip_ranges[array]:
if prefix['service'] == 'EC2' and prefix['region'] == self.args.region:
print(prefix[field])
if __name__ == '__main__':
iprangefinder = IPRangeFinder()
iprangefinder.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment