Skip to content

Commit

Permalink
Update ASN Lookup.py
Browse files Browse the repository at this point in the history
- Added Time Bar
- Added Hard Limit to ASN Amount
- Tweaked Code
  • Loading branch information
Zyrikwt authored Jul 19, 2023
1 parent a73df88 commit d622f41
Showing 1 changed file with 33 additions and 14 deletions.
47 changes: 33 additions & 14 deletions ASN Lookup/ASN Lookup.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
import requests
import json
import sys
import time
import random
import tqdm

def get_asn_info(asn_number):
"""Gets ASN information from the BGPView API."""
url = f'https://api.bgpview.io/asn/{asn_number}/prefixes'
response = requests.get(url)
data = response.json()
return data
try:
response = requests.get(url)
data = response.json()
return data
except requests.exceptions.RequestException as e:
raise ValueError(f'API returned an error: {e}')

def get_subnets(asn_info):
"""Gets the subnets associated with an ASN."""
subnets = []
for prefix in asn_info['data']['ipv4_prefixes']:
subnets.append(prefix['prefix'])
subnets = [
prefix['prefix']
for prefix in asn_info['data']['ipv4_prefixes']
]
return subnets

def write_subnets_to_file(subnets, file_name):
def write_subnets_to_file(subnets, file_name='ip_ranges.lst'):
"""Writes the subnets to a LST file."""
with open(file_name, 'w') as f:
for subnet in subnets:
Expand All @@ -28,18 +35,30 @@ def main():
max_asns = 20
print('** ASN to IP Range**')
print(f'Recommended: >{max_asns} ASNs.')
asn_numbers = input('Enter ASN(s): ').split(',')
try:
asn_numbers = input('Enter ASN(s): ').split(',')
except ValueError as e:
print(e)
sys.exit()
print('** Generating **')
subnets = []
for asn_number in asn_numbers:
asn_info = get_asn_info(asn_number)
subnets.extend(get_subnets(asn_info))
with tqdm.tqdm(total=len(asn_numbers), ncols=60) as pbar:
for asn_number in asn_numbers:
if len(asn_numbers) > max_asns:
print(f'Error: The maximum number of ASNs is {max_asns}.')
sys.exit()
try:
pbar.update(1)
asn_info = get_asn_info(asn_number)
except ValueError as e:
print(e)
continue
subnets.extend(get_subnets(asn_info))
file_name = 'ip_ranges.lst'
write_subnets_to_file(subnets, file_name)
write_subnets_to_file(subnets)

# Add completed text
print('** Completed **')
print(f'The file "ip_ranges.lst" has been generated.')
print(f'The file "{file_name}" has been generated.')

if __name__ == '__main__':
main()

0 comments on commit d622f41

Please sign in to comment.