-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_allocation.py
executable file
·76 lines (61 loc) · 2.47 KB
/
check_allocation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python
import json, requests, ipaddress
from argparse import ArgumentParser
__author__ = 'James Di Trapani <james@ditrapani.com.au>'
class BGPCheckAdvertisement():
"""
Wrapper for bgptoolkit.net that provides quick & useful information to console for a given IP.
Essential for any Network Engineers toolkit.
"""
def __init__(self, ip):
self.ip = ip
self.data = self.grab_information(self.ip)
def grab_information(self, query):
api_url = 'https://bgptoolkit.net/api/ca/{0}'.format(query)
session = requests.session()
get_data = session.get(api_url)
json_data = get_data.json()
return json_data
def parse_data(self):
if self.data['status'].lower() != 'ok':
print('{0}, please try again'.format(json_data['status_message']))
prefix_data = self.data['data']['prefixes']
prefix_list = []
for prefix in prefix_data:
prefix_list.append(prefix['prefix'])
most_specific = self.most_specific_subnet(prefix_list)
for prefix in prefix_data:
if ipaddress.ip_network(prefix['prefix']) == ipaddress.ip_network(most_specific):
prefix_data = prefix
prefix_data['asn']['asn'] = f'AS{prefix_data["asn"]["asn"]}'
self.print_output(self.ip, self.data['data']['ptr_record'], prefix_data, self.data, len(self.data['data']['prefixes']))
def most_specific_subnet(self, prefix_list):
current_specific = ipaddress.ip_network(u'0.0.0.0/0')
for prefix in prefix_list:
prefix = ipaddress.ip_network(prefix)
subnet_of = prefix.subnet_of(current_specific)
if subnet_of:
current_specific = prefix
return current_specific
def print_output(self, query, ptr, pd, jd, ta):
print(f'\nIP: {query}')
print(f'PTR Record: {ptr}\n')
print(f'Total Advertisements: {ta}')
print(f'Advertised Prefix: {pd["prefix"]}')
print(f'Advertised by: {pd["asn"]["asn"]} - {pd["asn"]["description"]}\n')
print(f'Allocation RIR: {jd["data"]["rir_allocation"]["rir_name"]}')
print(f'Allocation Country: {pd["country_code"]}')
print(f'Allocation Company: {pd["asn"]["description"]}')
print(f'Allocated Date: {jd["data"]["rir_allocation"]["date_allocated"]}\n')
if __name__ == "__main__":
parser = ArgumentParser(
description = 'Display information on the current allocation of a sub aggregate address'
)
parser.add_argument(
'ip',
type = str,
help = 'IPv4 or IPv6 sub aggregate address you wish to recieve information on'
)
arguments = parser.parse_args()
current_allocation = BGPCheckAdvertisement(arguments.ip)
current_allocation.parse_data()