-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeobox.py
executable file
·72 lines (56 loc) · 1.99 KB
/
geobox.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
#!/usr/bin/python3
# Shoddy python disclaimer: I don't really use python so this script can probably be cleaned up a lot
import sys
from datetime import datetime
import requests
if len(sys.argv) != 4:
print('Usage: python3 geobox.py <url to netbox instance> <netbox api key> <output location>')
exit()
netboxBase = sys.argv[1]
netboxKey = sys.argv[2]
outputFile = sys.argv[3]
prefixes = []
nextURL = netboxBase + '/api/ipam/prefixes/'
while nextURL is not None:
print('Fetching geofeed from ' + nextURL)
r = requests.get(nextURL, headers={
'Accept': 'application/json',
'Authorization': 'Token ' + netboxKey
})
data = r.json()
if r.status_code < 200 or r.status_code > 299:
print('Error while fetching prefixes: ', data)
exit()
nextURL = data['next']
results = data['results']
prefixes.extend(results)
print('Got ' + str(len(results)) + ' prefixes')
print('Found a total of ' + str(len(prefixes)) + ' prefixes')
print('Building geofeed')
i = 0
feed = '# Generated with GeoBox (https://github.com/FrumentumNL/GeoBox) on ' + datetime.now().isoformat() + '\n'
for entry in prefixes:
fields = entry['custom_fields']
if not fields['geoloc_has_location']:
# Explicitly no geoloc, all fields should be empty
feed += entry['prefix'] + ',,,,\n'
i += 1
continue
country = fields['geoloc_country']
region = fields['geoloc_region']
city = fields['geoloc_city']
if country is None and region is None and city is None:
# Just let it inherit
continue
country = '' if country is None else country
region = '' if region is None else region
city = '' if city is None else city
feed += entry['prefix'] + ',' + country + ',' + region + ',' + city + ',\n'
i += 1
print('Geofeed built, contains ' + str(i) + ' prefixes')
print('Saving to ' + outputFile)
f = open(outputFile, "w")
f.write(feed)
f.close()
print('Saved to ' + outputFile)
print('Finished! Thanks for using GeoBox.')