1

我能够让 geolite2 在 python2.7 上工作 - 但我需要 3.4。我在此链接上找到了 2.7 的说明:http: //pythonhosted.org/python-geoip/。还提供了代码片段。

pip install python-geoip
pip install python-geoip-geolite2
>>> from geoip import geolite2
>>> match = geolite2.lookup('17.0.0.1')
>>> match is not None
True

所以我很自然地将所有 pip 更改为 pip3 并安装在新的 VM 上。代码没有错误,但它不会从它们的数据库中查找和返回值。

pip3 install python-geoip
pip3 install python-geoip-geolite2

在 2.7 VM 中,当我使用 3.4 时,我将 geoip lib 指向 /usr/local/lib/python2.7/dist-packages - 也没有运气。但是,它适用于同一 VM 上的 2.7。

我需要做什么才能使其在 3.4 上运行?

4

4 回答 4

6

python-geoip不支持Python 3,两年没更新了。尽管有一个添加 Python 3 支持的拉取请求,但我不希望它很快被合并和发布。我建议改用官方的 MaxMindgeoip2

于 2015-09-15T13:53:17.383 回答
4

安装:

apt install python3-pip
pip3 install maxminddb 
pip3 install maxminddb-geolite2

示例使用:

#!/usr/bin/python3
# coding=utf-8

from geolite2 import geolite2

reader = geolite2.reader()

# google's ip
match = reader.get('172.217.16.163')
if match:
  # print(match)
  if 'country' in match:
    print(match['country']['iso_code'])
  else:
    print(match['continent']['code'])
else:
  print('') 
于 2020-08-09T16:20:46.203 回答
0

python-geoip使用 python 3 支持(使用pipor安装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)
于 2020-10-03T11:28:11.267 回答
-1

要使用 maxmind 数据库:

安装:

maxminddb 
maxminddb-geolite

在您的代码中:

from geolite2 import geolite2

match = geolite2.reader()
geoip = match.get('xxx.xxx.xxx.xxx')
于 2020-01-31T16:14:05.297 回答