Python – Use RIPE to Research IP Subnet (BGP AS, Geolocation, Reverse DNS, CIDR Block, & Registration)

# Author: Kerry Cordero
# Version: 1.0.0
# Description: This script will use RIPE to Research IP Subnet (BGP AS, Geolocation, Reverse DNS, CIDR Block, & Registration)

import requests
import json

def user_input():
    ip_address = input('Enter the IP address to query: ')
    return ip_address

def query_ripe(ip_address):
    rev_dns_record = 'No reverse record found'
    asinfo_result = 'No AS information found'
    as_text = 'None'

    ipinfo = requests.get(f"https://stat.ripe.net/data/network-info/data.json?resource={ip_address}")
    if ipinfo.status_code == 200:
        ipinfo_data = ipinfo.json()
        if ipinfo_data['data']['asns'] != []:
            as_number = ipinfo_data['data']['asns']
            as_text = ''.join(as_number)

            asinfo = requests.get(f"https://stat.ripe.net/data/as-overview/data.json?resource=AS{as_text}")
            if asinfo.status_code == 200:
                asinfo_data = asinfo.json()
                asinfo_result = asinfo_data['data']['holder']

        rev_dns = requests.get(f"https://stat.ripe.net/data/reverse-dns-ip/data.json?resource={ip_address}")
        if rev_dns.status_code == 200:
            rev_dns_data = rev_dns.json()
            rev_dns_result = rev_dns_data['data']['result']
            if rev_dns_result is not None:
                rev_dns_record = ''.join(rev_dns_result)

        geoloc = requests.get(f"https://stat.ripe.net/data/geoloc/data.json?resource={ip_address}")
        if geoloc.status_code == 200:
            geoloc_data = geoloc.json()
            location = geoloc_data['data']['located_resources']
            location_data = dict(location[0])
            locations = location_data['locations']
            country_data = locations[0]
            country = country_data['country']

        print(f'''
        Results for IP address: {ip_address}
        CIDR address block: {ipinfo_data['data']['prefix']}
        Announced by BGP AS: {as_text}
        Registration information: {asinfo_result}
        Reverse DNS Lookup: {rev_dns_record}
        Geolocation country: {country}''')

        print('''
        --------------------------------------------------------------------------------------------
        ''')

print('''
--------------------------------------------------------------------------------------------
This script will gather background information on an IP address using the RIPEStat API
''')
ip_address = user_input()
query_ripe(ip_address)

EXAMPLE OUTPUT:

Enter the IP address to query: 4.2.2.0/24

        Results for IP address: 4.2.2.0/24
        CIDR address block: 4.0.0.0/9
        Announced by BGP AS: 3356
        Registration information: LEVEL3
        Reverse DNS Lookup: No reverse record found
        Geolocation country: US