Python – Find ASN and Subnets using an IP Address


whois -h " -v [IP_ADDRESS]"
whois -h -- '-i origin ASXXXXX | grep -Eo "([0-9.]+){4}/[0-9]+"



#This script will prompt for an IP Address.  It will take that IP, find the ASN, then find all subnets for that ASN
#By:  Kerry Cordero

import requests
from ipwhois import IPWhois
from prettytable import PrettyTable

# Prompt for IP Address
ip_address = input("Please enter an IP address: ")

# Perform a lookup on the IP address
ipwhois = IPWhois(ip_address)
result = ipwhois.lookup_rdap(depth=1)

# Get the ASN Description and Number
asn_description = result['asn_description']
asn_number = result['asn']

# Get the subnets related to the ASN number from the BGPView API
response = requests.get(f'{asn_number}/prefixes')
data = response.json()

# Extract the subnets
subnets = [prefix['prefix'] for prefix in data['data']['ipv4_prefixes']]

# Create a PrettyTable object
table = PrettyTable()

# Define the table columns
table.field_names = ["IP Address", "ASN Description", "ASN Number", "Subnets"]

# Add rows to the table
for subnet in subnets:
    table.add_row([ip_address, asn_description, asn_number, subnet])

# Print the table