python 获取ip信息(国家、城市等)

python 获取ip信息(国家、城市等)

安装geoip2包:pip install geoip2
下载数据库文件:http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz
解压出GeoLite2-City.mmdb文件
新建py文件,内容如下:

import geoip2.database

reader = geoip2.database.Reader('./GeoLite2-City.mmdb')  # mmdb文件路径
c= reader.country('123.123.123.123')
print c.country.names   # 国家名
print c.country.code  # 国家代码
# 其他信息看源码

** 以下为配置自动更新数据库的步骤 **

在github下载geoipupdate最新包:geoipupdate-3.1.1.tar.gz
解压并安装:

tar -zxvf geoipupdate-3.1.1.tar.gz
./configure
sudo make
sudo make install 

修改配置文件:/usr/local/etc/GeoIP.conf

# The following AccountID and LicenseKey are required placeholders.
# For geoipupdate versions earlier than 2.5.0, use UserId here instead of AccountID.
AccountID 0 
LicenseKey 000000000000 
 
# Include one or more of the following edition IDs: 
# * GeoLite2-City - GeoLite 2 City 
# * GeoLite2-Country - GeoLite2 Country 
# For geoipupdate versions earlier than 2.5.0, use ProductIds here instead of EditionIDs.
EditionIDs GeoLite2-City GeoLite2-Country

执行更新:
/usr/local/bin/geoipupdate

添加crontab实现每周更新:crontab -e
0 0 * * 0 /usr/local/bin/geoipupdate

你可能感兴趣的:(Python)