-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws_ip_check.py
54 lines (43 loc) · 1.32 KB
/
aws_ip_check.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
Check if one or more IP address or CIDR block is in an AWS IP range.
Usage:
python aws_ip_check.py IP [IP ...]
Arguments:
IP IP address or CIDR block
Prerequisites:
Python 3.6+
Install required packages:
pip install -r requirements.txt
"""
import ipaddress
import requests
import json
import click
response = requests.get("https://ip-ranges.amazonaws.com/ip-ranges.json")
try:
data = response.json()
except json.decoder.JSONDecodeError:
print("Error: Could not decode JSON response from AWS.")
exit(1)
@click.command()
@click.argument("ip", nargs=-1, required=True, type=str)
def check_ip(ip):
"""Check if an IP address or CIDR block is in an AWS IP range."""
output = []
for prefix in data["prefixes"]:
try:
if ipaddress.ip_address(ip) in ipaddress.ip_network(prefix["ip_prefix"]):
output.append(prefix)
except ValueError:
try:
if ipaddress.ip_network(ip).subnet_of(
ipaddress.ip_network(prefix["ip_prefix"])
):
output.append(prefix)
except ValueError:
print(f"Invalid IP address or CIDR block: {ip}")
if output:
click.echo(json.dumps(output, indent=4))
return output
if __name__ == "__main__":
check_ip()