IP Geolocation
Revision as of 15:22, 13 November 2019 by Rafahsolis (talk | contribs) (Created page with "<syntaxhighlight lang="bash"> pip install geoip2 </syntaxhighlight><syntaxhighlight lang="python3"> #!/root/.virtualenvs/geoip/bin/python import sys from geoip2 import databas...")
pip install geoip2
#!/root/.virtualenvs/geoip/bin/python
import sys
from geoip2 import database
DB_PATH = '/usr/share/geoip/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')