#!/usr/bin/python # Name: aws_ip_ranges # Written by: Jim Cameron # Created: 2017-02-21 # Last updated: 2017-02-21 # Version: 1.0 # # Purpose: Parse a JSON file downloaded from # https://ip-ranges.amazonaws.com/ip-ranges.json that contains a list of the # IP address ranges used by Amazon Web Services (AWS). See # http://support.moonpoint.com/languages/python/aws for example output. import getopt, json, os.path, urllib2, sys inputfile = "" # Print usage information def usage(): print 'Usage: aws_ip_ranges [-hd] [-i inputfile]' print print '-h --help print this message' print '-d --download download the current JSON data from Amazon' print '-i, --input input_file use input file' # Download current JSON data from Amazon def downloadJSONdata(): url = "https://ip-ranges.amazonaws.com/ip-ranges.json" outfile = "ip-ranges.json" page = urllib2.urlopen(url) source=page.read() f=open(outfile, 'w') f.write(source) f.close() try: opts, args = getopt.getopt(sys.argv[1:], "hdi:", ["help","download","input="]) except getopt.GetoptError as err: # print help information and exit print str(err) usage() sys.exit(2) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() elif o in ('-d', '--download'): downloadJSONdata() elif o in ('-i', '--input'): inputfile = a else: assert False, "unhandled option" # if the input file isn't specified assume it is a file named ip-ranges.json # in the current directory if not inputfile: inputfile = 'ip-ranges.json' if not os.path.isfile(inputfile): print "Input file ", inputfile, "not found" print "Use", sys.argv[0], "-d or --download to download ip-ranges.json" sys.exit(2) else: data = json.load(open(inputfile)) # Print the data left-justified in 3 columns of 20 characters in length print "IP Prefix".ljust(20) + "Region".ljust(20) + "Service".ljust(20) for d in data["prefixes"]: print d["ip_prefix"].ljust(20) + d["region"].ljust(20) + d["service"].ljust(20)