-
Notifications
You must be signed in to change notification settings - Fork 0
/
geolocation_sources.py
96 lines (30 loc) · 1.28 KB
/
geolocation_sources.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
import subprocess
from re import findall
from iso3166 import countries, countries_by_alpha3
class IPGeolocationSource:
def __init__(self):
self.description = "Sample description"
self.countries = countries_by_alpha3.keys()
self.ip_geolocation_report_template = {c: 0 for c in self.countries}
def generate_ip_geolocation_report(self, ip_list):
report = self.ip_geolocation_report_template
for ip in ip_list:
try:
country = countries.get(self.geolocate_ip(ip)).alpha3
except KeyError:
print("Couldn't get a location from {}".format(ip))
report[country] = report.get(country) + 1
return report
def geolocate_ip(self, ip):
pass
class GeoIPLookup(IPGeolocationSource):
def __init__(self):
super(GeoIPLookup, self).__init__()
# can verify credentials here e.g. for login sources
pass
def geolocate_ip(self, ip):
output = subprocess.check_output(["geoiplookup", ip],
stderr=subprocess.STDOUT).decode("UTF-8")
if "IP Address not found" in output:
return None
return findall("(?<=: )(\w{2})(?=,)", output)[0]