2022-06-25 22:27:01 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
"""MODULE: Provides functions to call various APIs to retrieve IP/prefix information."""
|
|
|
|
|
|
|
|
import ipaddress
|
2023-06-04 12:06:30 +01:00
|
|
|
|
2022-06-25 22:27:01 +01:00
|
|
|
import requests
|
|
|
|
|
|
|
|
|
2023-06-04 12:06:30 +01:00
|
|
|
def get_ip_information(ipv4_address: ipaddress.IPv4Address) -> dict | None:
|
2022-06-25 22:27:01 +01:00
|
|
|
"""Retrieves information about a given IPv4 address from IP-API.com."""
|
2023-06-04 12:06:30 +01:00
|
|
|
api_endpoint: str = f"http://ip-api.com/json/{ipv4_address}"
|
2022-06-26 00:15:27 +01:00
|
|
|
try:
|
2023-06-04 12:06:30 +01:00
|
|
|
resp: requests.Response = requests.get(api_endpoint, timeout=10)
|
2022-06-26 00:15:27 +01:00
|
|
|
resp.raise_for_status()
|
2023-06-04 12:06:30 +01:00
|
|
|
ret: dict | None = resp.json() if resp.json().get("status") == "success" else None
|
2022-06-26 00:15:27 +01:00
|
|
|
except (requests.exceptions.JSONDecodeError, requests.exceptions.HTTPError):
|
|
|
|
ret = None
|
|
|
|
return ret
|
2022-06-25 22:27:01 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_autonomous_system_number(as_info: str) -> str:
|
|
|
|
"""Parses AS number from provided AS information."""
|
2023-06-04 12:06:30 +01:00
|
|
|
as_number: str = as_info.split(" ")[0]
|
2022-06-25 22:27:01 +01:00
|
|
|
return as_number
|
|
|
|
|
|
|
|
|
2023-06-04 12:06:30 +01:00
|
|
|
def get_prefix_information(autonomous_system: str) -> list | None:
|
2022-06-25 22:27:01 +01:00
|
|
|
"""Retrieves prefix information about a given autonomous system."""
|
2023-06-04 12:06:30 +01:00
|
|
|
api_endpoint: str = f"https://api.hackertarget.com/aslookup/?q={str(autonomous_system)}"
|
2022-06-26 00:15:27 +01:00
|
|
|
try:
|
2023-06-04 12:06:30 +01:00
|
|
|
resp: requests.Response = requests.get(api_endpoint, timeout=10)
|
2022-06-26 00:15:27 +01:00
|
|
|
resp.raise_for_status()
|
|
|
|
except requests.exceptions.HTTPError:
|
|
|
|
return None
|
2023-06-04 12:06:30 +01:00
|
|
|
prefixes: list[str] = resp.text.split("\n")
|
2022-06-25 22:27:01 +01:00
|
|
|
prefixes.pop(0)
|
|
|
|
return prefixes
|