Skip to content

Instantly share code, notes, and snippets.

@safebuffer
Created April 12, 2021 21:50
Show Gist options
  • Save safebuffer/88b4c8ea42cbb4e8ca821ed9185661c0 to your computer and use it in GitHub Desktop.
Save safebuffer/88b4c8ea42cbb4e8ca821ed9185661c0 to your computer and use it in GitHub Desktop.
ASN To IP List
import argparse
import time
import os
import platform
from requests import get as http_get
from netaddr import IPNetwork
def logprint(string):
now = time.time()
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
s = "%02d/%3s/%04d %02d:%02d:%02d" % (
day, monthname[month], year, hh, mm, ss)
ll = "%s - [%s] %s" % ("bgpview-report", s, string)
if platform.system() == "Windows":
print(ll)
else:
sys.stderr.write('\033[94m' + ll + '\033[0m')
def get_req(rr):
try:
info = http_get(rr)
dinfo = info.json()
if dinfo['status'] == "ok":
return dinfo['data']
except Exception as e:
logprint(f"[-] error while sending get request to {rr} ")
return False
def main(asnlist):
asnlist = asnlist.split(',')
for asn in asnlist:
asn = asn.replace('AS','')
savefile = f"{asn}.txt"
try:
os.remove(savefile)
except Exception as e:
pass
logprint(f"[*] Getting {asn} info ")
info = get_req(f"https://api.bgpview.io/asn/{asn}")
if info:
logprint(f"[*] Getting {info['name']} data ")
logprint(f"[*] Country code {info['country_code']} ")
logprint(f"[*] Traffic ratio {info['traffic_ratio']} ")
logprint(f"[*] Description {info['description_short']} ")
else:
logprint(f"[-] error Getting {asn} info ")
ipv4p = get_req(f"https://api.bgpview.io/asn/{asn}/prefixes")
if ipv4p:
for ipv4cidr in ipv4p['ipv4_prefixes']:
cidr = ipv4cidr['prefix']
logprint(f"[*] Loading {ipv4cidr['prefix']} {ipv4cidr['name']} ")
for ip in IPNetwork(cidr):
open(savefile,'a').write(str(ip)+'\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help = True, description = "bgpview report")
parser.add_argument("asn", help="asn list eg 'AS15830,AS9121'")
options = parser.parse_args()
main(options.asn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment