Python/Python for Windows

python을 이용한 IIS web log 분석 (3) - 클라이언트 IP 국가식별

Pydole 2019. 7. 15. 12:41

이번 포스팅은 웹 로그 중 CIP(클라이언트 IP)를 이`용하여 국가식별을 하려고 한다.

국가식별을 하는 이유는 크게 2가지로 볼 수 있는데,

 

 1. 국가별 인입 통계

 2. 해외IP인입을 확인 및 차단하는 데 활용. (국내 서비스 일경우)

 

 

우선 GeoLite2 라는 국가DB를 다운받아서, CIP를 DB에 대입하여 국가정보를 추출하겠다.

 

https://dev.maxmind.com/geoip/geoip2/geolite2/

 

GeoLite2 Free Downloadable Databases « MaxMind Developer Site

GeoLite2 Free Downloadable Databases GeoLite Legacy databases were discontinued on January 2, 2019. Learn more. Databases GeoLite2 databases are free IP geolocation databases comparable to, but less accurate than, MaxMind’s GeoIP2 databases. The GeoLite2 C

dev.maxmind.com

 

파일을 받고, 적당한 곳에 압축을 푼다.

 

API를 파이썬(python)으로 할 것이 때문에, geoip2를 설치한다. 설치 방법은 pip install geoip2 하면 된다

 

python API : https://pypi.org/project/geoip2/

 

 

geoip2

MaxMind GeoIP2 API

pypi.org

 

 

 

from datetime import datetime
from datetime import timedelta

import geoip2.database

 

reader = geoip2.database.Reader('C:\DB\GeoLite2-city.mmdb')  # path

 


with open(r'C:\log\sample.log', encoding='utf-8', errors='replace') as f:
      lines = f.readlines()
      for cnt, line in enumerate(lines,0):
           logs = line.split(' ')
           logtime = logs[0] + ' ' + logs[1]

           try:
                logtime = datetime.strptime(logtime, '%Y-%m-%d %H:%M:%S')                                  - timedelta(hours=-9)

           except ValueError:
                 pass

           try:
                response = reader.city(logs[10])
                country = response.country.iso_code

               if country != 'KR':
                     print(country)

              except ValueError:
                   pass

             except IndexError:
                   pass

             except geoip2.errors.AddressNotFoundError:
                   country = None

 

 

 

CIP별로 국가별 ISO_Code가 추출됨을 알 수 있다.