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

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

安装geoip2包:pip install geoip2
下载数据库文件:http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz,解压出GeoLite2-City.mmdb文件
现在需要注册账号后才能下载mmdb文件,请参考官方文档:
https://dev.maxmind.com/geoip/geoip2/geolite2/

新建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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值