准備工作
要關聯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地址,查查看地址:

查詢結果

