Skip to content

Instantly share code, notes, and snippets.

@maxrp
Last active October 10, 2019 18:48
Show Gist options
  • Save maxrp/7d77853435ffba005560e8279a675d05 to your computer and use it in GitHub Desktop.
Save maxrp/7d77853435ffba005560e8279a675d05 to your computer and use it in GitHub Desktop.
Which AWS service does this IP belong to?
#!/usr/bin/env python3
"""
This tool parses the big blob of JSON IP range mappings for AWS and prints
which service and availability zone the IP occurs in.
It expects to find ip-ranges.json in it's PWD.
To update the JSON blob:
wget https://ip-ranges.amazonaws.com/ip-ranges.json
"""
import json
import sys
from time import strftime, strptime
from IPy import IP
CREATE_FMT = "%Y-%m-%d-%H-%M-%S"
def usage(err):
hint = "\033[1mHint:\033[0m"
err_name = err.__class__.__name__
print(f"Usage: {sys.argv[0]} -h|--help\n"
f" {sys.argv[0]} 127.0.0.1\n")
if err_name == "IndexError":
print(hint, "missing an IP to look up.")
if err_name == "ValueError":
if sys.argv[1][0] is not "-":
print(hint, f"{sys.argv[1]} is not an IP.")
def refine_types(entry):
if 'createDate' in entry:
ctime = strptime(entry['createDate'], CREATE_FMT)
entry['createDate'] = strftime("%c", ctime)
for key_name in ['ip_prefix', 'ipv6_prefix']:
if key_name in entry:
entry['prefix'] = IP(entry[key_name])
del entry[key_name]
return entry
def main(query_ip):
print(f"Looking up {query_ip}...", end=" ")
with open("ip-ranges.json") as ip_range_file:
ranges = json.load(ip_range_file, object_hook=refine_types)
print(f" using data from: {ranges['createDate']}")
found = False
for entry in ranges['prefixes'] + ranges['ipv6_prefixes']:
if query_ip in entry['prefix']:
print(f"{query_ip} is an {entry['service']} IP available in the "
f"{entry['region']} region.")
found = True
if not found:
print(f"{query_ip} is not an Amazon IP.")
if __name__ == '__main__':
try:
if sys.argv[1] in ['-h', '--help']:
print(__doc__.lstrip())
except IndexError as err:
usage(err)
sys.exit(127)
else:
try:
QUERY = IP(sys.argv[1])
except ValueError as err:
usage(err)
else:
main(QUERY)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment