#!/usr/bin/python
from datetime import datetime
import requests
import json
import argparse
parser = argparse.ArgumentParser(description="AWS IP Range Display")
parser.add_argument('-verbose', '-v', action='count', help='Verbose')
parser.add_argument('--region', '-r', help="Region to print",
default='ap-southeast-2')
parser.add_argument('--service', '-s', help="Service to print", default='ec2')
parser.add_argument('--listservices', default=False, action='store_true')
parser.add_argument('--listregions', default=False, action='store_true')
args = parser.parse_args()
resp = requests.get("https://ip-ranges.amazonaws.com/ip-ranges.json")
if resp.status_code != 200:
print("Failed to get JSON from {}: {}".format(url, resp.status_code))
sys.exit(1)
d = json.loads(resp.text)
if args.verbose > 1:
print(json.dumps(d, sort_keys=True, indent=4, separators=(',', ': ')))
created = datetime.strptime(d['createDate'], "%Y-%m-%d-%H-%M-%S")
if args.verbose:
print("File created %d days ago (%s), sync token %s" %
((datetime.now() - created).days, d['createDate'], d['syncToken']))
if args.listregions:
print(json.dumps(sorted(set([prefix['region'].lower() for
prefix in d['prefixes']]))))
elif args.listservices:
print(json.dumps(sorted(set([prefix['service'].lower() for
prefix in d['prefixes']]))))
else:
for prefix in d['prefixes']:
if prefix['service'].lower() == args.service.lower():
if ((prefix['region'].lower() == args.region.lower() or
prefix['region'].lower() == 'global')):
print(prefix['ip_prefix'])