Difference between revisions of "IP Geolocation"
Jump to navigation
Jump to search
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...") Tag: visualeditor |
Rafahsolis (talk | contribs) m Tag: visualeditor |
||
| Line 1: | Line 1: | ||
| − | <syntaxhighlight lang="bash"> | + | Download GeoIP Database from: |
| + | |||
| + | https://dev.maxmind.com/geoip/geoip2/geolite2/ | ||
| + | |||
| + | Install requirements<syntaxhighlight lang="bash"> | ||
pip install geoip2 | pip install geoip2 | ||
</syntaxhighlight><syntaxhighlight lang="python3"> | </syntaxhighlight><syntaxhighlight lang="python3"> | ||
| − | #!/ | + | #!/usr/bin/python3 |
import sys | import sys | ||
from geoip2 import database | from geoip2 import database | ||
| − | DB_PATH = '/ | + | DB_PATH = '/path/to/GeoIP2-City.mmdb' |
class Geolocator(object): | class Geolocator(object): | ||
Latest revision as of 15:25, 13 November 2019
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')