python3中使用GeoIP来查找IP信息

简介

本文介绍使用GeoIP来查找IP信息

环境

  • python3
  • geoip2

GeoIP数据库下载

wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz
gunzip GeoLite2-Country.mmdb.gz
wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
gunzip GeoLite2-City.mmdb.gz

查询代码

import geoip2.database
import sys

ip = input()

reader = geoip2.database.Reader('./GeoLite2-City.mmdb')

data = reader.city(ip)

print ("IP Address: ", ip)
print ("Country:", data.country.name)
print ("Subdivisions: ", data.subdivisions.most_specific.name)
print ("City: ", data.city.name)
print ("Latitude: ", data.location.latitude)
print ("Longitude: ", data.location.longitude)

运行结果

$ python3 main.py 
172.104.68.126
IP Address:  172.104.68.126
Country: Japan
Subdivisions:  Tokyo
City:  Tokyo
Latitude:  35.685
Longitude:  139.7514

本文源码

https://github.com/cangyan/TAV/tree/master/00017_PYTHON_GEO_IP

发表评论

电子邮件地址不会被公开。 必填项已用*标注