python绝技 — 使用PyGeoIP关联IP地址和物理位置

mac2022-06-30  102

准备工作

要关联IP与物理位置,我们需要有一个包含这样对应关系的数据库。

我们可以使用开源数据库GeoLiteCity,它能够较为准确地把IP地址与所在城市关联起来

下载地址:http://dev.maxmind.com/geoip/legacy/geolite/

下载之后我们解压:xz -d GeoLiteCity.dat.xz,如:/My/lib/ip/GeoLiteCity.dat

 

安装pygeoip库。这个库用于对GeoLiteCity数据库的查询 

 

代码:

 

#!/usr/bin/python #--*--coding=utf-8--*-- import pygeoip gi = pygeoip.GeoIP('/My/lib/ip/GeoLiteCity.dat') def printRecord(tgt): rec = gi.record_by_addr(tgt) city = rec['city'] region = rec['region_code'] country = rec['country_name'] long = rec['longitude'] lat = rec['latitude'] print '[*] 主机: ' + tgt + ' Geo-located.' print '[+] ' + str(city) + ', ' +str(region)+', '+str(country) print '[+] 经度: '+str(lat)+', 维度: '+ str(long) tgt = '183.141.110.74' printRecord(tgt)

183.141.110.74是随便找的一个代理ip地址,查查看地址:

查询结果

 

转载于:https://www.cnblogs.com/ssooking/p/6097436.html

最新回复(0)