准备工作:
先去 https://www.maxmind.com/ 注册一个帐号
然后去github
下载geoipupdate
https://github.com/maxmind/geoipupdate/releases
下载对应系统的安装包1
rpm -ivh geoipupdate.rpm
编辑配置文件1
vi /etc/GeoIP.conf
访问 https://www.maxmind.com/en/my_license_key ,自己新建一个更新的LicenseKey。
配置好后运行1
geoipupdate
就会在/usr/share/GeoIP/
目录下生成离线数据库文件了。
以后需要更新IP库,直接运行geoipupdate
。就能更新到最新的IP地址库了。
使用Geoip2
python3环境下pip安装
1 | yum install python3 gcc python-devel |
新建文件findip.py1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#!/usr/bin/env python3
# coding=utf-8
import geoip2.database
import sys
def from_ip_get_info(sip):
reader = geoip2.database.Reader(
'/usr/share/GeoIP/GeoLite2-City.mmdb')
try:
response = reader.city(sip)
try:
city = response.city.names.get(u'zh-CN', response.city.name)
country = response.registered_country.names.get(u'zh-CN')
if not city:
city = response.country.names.get(u'zh-CN')
except Exception as e:
logging.debug("read Geolite2-City.mmdb error:%s" % e)
city = ''
longitude = response.location.longitude
latitude = response.location.latitude
subdivisions = response.subdivisions.most_specific.names.get(
u'zh-CN', "")
except Exception as ex:
logging.debug("from_ip_get_info:%s" % ex)
return None
return (
sip,
country,
city,
subdivisions,
longitude,
latitude
)
if __name__ == "__main__":
a = from_ip_get_info(sys.argv[1])
print (a)
使用方法:1
./findip.py 5.188.201.227