IP Geolocation
Revision as of 15:25, 13 November 2019 by Rafahsolis (talk | contribs)
Download GeoIP Database from:
https://dev.maxmind.com/geoip/geoip2/geolite2/
Install requirements
pip install geoip2
#!/usr/bin/python3
import sys
from geoip2 import database
DB_PATH = '/path/to/GeoIP2-City.mmdb'
class Geolocator(object):
def __init__(self, ip):
self.ip = ip
self.city = self.read_city()
def read_city(self):
reader = database.Reader(DB_PATH)
city = reader.city(self.ip)
reader.close()
return city
@property
def location(self):
return "{city} ({country})".format(city=unknown_if_none(self.city.city.name), country=unknown_if_none(self.city.country.name))
def unknown_if_none(text):
if text is None:
return 'Unknown'
return text
if __name__ == '__main__':
try:
ip = sys.argv[1]
locator = Geolocator(ip)
print(locator.location)
except:
print('Unknown')