With Python2 now EOL, one of my tasks was to replace old python2/geolite2 code with python3/geoip. This does require a subscription to MaxMind to either make the calls via web or download static database files, which fortunately was a option.
Installing Python3 GeoIP2 package
On Ubuntu 20:
- apt install python3-pip
- pip3 install geoip2
On FreeBSD 11.4:
- pkg install python3
- pkg install py37-pip
- pip install geoip2
Verify successful install
% python3
Python 3.7.8 (default, Aug 8 2020, 01:18:05)
[Clang 8.0.0 (tags/RELEASE_800/final 356365)] on freebsd11
Type "help", "copyright", "credits" or "license" for more information.
>>> import geoip2.database
>>> help(geoip2.database.Reader)
Help on class Reader in module geoip2.database:
Sample Python Script
#!/usr/bin/env python3
import sys
import geoip2.database
ipv4_address = input("Enter an IPv4 address: ")
with geoip2.database.Reader('/var/db/GeoIP2-City.mmdb') as reader:
try:
response = reader.city(ipv4_address)
except:
sys.exit("No info for address: " + ipv4_address)
if response:
lat = response.location.latitude
lng = response.location.longitude
city = response.city.name
print("lat: {}, lng: {}, city: {}".format(lat, lng, city))