python-geoip
使用 python 3 支持(使用pip
or安装pip3
):
pip3 install python-geoip-python3
输出:
Collecting python-geoip-python3
Downloading python_geoip_python3-1.3-py2.py3-none-any.whl (7.4 kB)
Installing collected packages: python-geoip-python3
Successfully installed python-geoip-python3-1.3
对于geolite2
:
pip3 install python-geoip-geolite2
输出:
Successfully built python-geoip-geolite2
Installing collected packages: python-geoip-geolite2
Successfully installed python-geoip-geolite2-2015.303
示例test_geoip.py
:
#!/usr/bin/env python3
import socket
from geoip import geolite2
import argparse
import json
# Setup commandline arguments
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname", required=True)
# Parse arguments
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)
print("IP address: {0}".format(ip_address))
match = geolite2.lookup(ip_address)
if match is not None:
print('Country: ',match.country)
print('Continent: ',match.continent)
print('Time zone: ', match.timezone)
print('Location: ', match.location)
跑:
python3 test_geoip.py --hostname=amazon.co.uk
输出:
IP address: 178.236.7.220
Country: IE
Continent: EU
Time zone: Europe/Dublin
Location: (53.3478, -6.2597)
再次运行:
python3 test_geoip.py --hostname=amazon.co.uk
输出:
IP address: 54.239.34.171
Country: US
Continent: NA
Time zone: America/Los_Angeles
Location: (47.6103, -122.3341)