環境はCentOS7.3で、Python3.4.3で確認した。
まずMAX MIND社[GeoLite2]からGeoLite2データベースを取得する。
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
gzipで圧縮されているので解凍する。
gunzip -d GeoLite2-City.mmdb.gz
続いて、PythonのGeoIPライブラリをインストールする。
/usr/local/python-3.4/bin/pip install geoip2
後は、Pythonでgeoip2.databaseをimportして使用する。
一先ずClassにして必要そうな値を返すサンプルを作成。
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
import sys
import geoip2.database
class GeoIP:
def __init__(self):
self.reader=geoip2.database.Reader('GeoLite2-City.mmdb')
def getGeoLocation(self,ip):
record = self.reader.city(ip)
return(record.country.name,record.city.name,record.country.iso_code,record.location.latitude,record.location.longitude)
if __name__== "__main__":
if len(sys.argv) == 2:
ipadress = sys.argv[1]
else:
ipadress = '8.8.8.8'
geodata = GeoIP()
print(geodata.getGeoLocation(ipadress)[0])
print(geodata.getGeoLocation(ipadress)[1])
print(geodata.getGeoLocation(ipadress)[2])
print(geodata.getGeoLocation(ipadress)[3])
print(geodata.getGeoLocation(ipadress)[4])
IPアドレス8.8.8.8で実行した結果は下記のようになる。
United States Mountain View US 37.386 -122.0838
サンプルには含めていないものもあるが、それぞれの変数は下記のようになる。
| 変数 | 意味 | 例 |
|---|---|---|
| record.continent.name | 大陸名 | North America |
| record.continent.code | 大陸コード | NA |
| record.country.name | 国名 | United States |
| record.country.iso_code | 国名コード | US |
| record.subdivisions.most_specific.name | 州・県 | California |
| record.subdivisions.most_specific.iso_code | 州・県コード | CA |
| record.city.name | 都市名 | Mountain View |
| record.location.latitude | 都市の緯度 | 37.386 |
| record.location.longitude | 都市の経度 | -122.0838 |
| record.location.time_zone | 都市のタイムゾーン | America/Los_Angeles |
日本語のデータベース
mmdbを下記のように読むと、日本語のデータベースを読み込んでくれる。
self.reader=geoip2.database.Reader('GeoLite2-City.mmdb',['ja'])
8.8.8.8を調べると下記のように出力される。ただ、場所によっては日本語が無いようなので、英語のままの方が良い気がする。
アメリカ合衆国 マウンテンビュー US 37.386 -122.0838

