-
python을 이용한 IIS web log 분석 (3) - 클라이언트 IP 국가식별Python/Python for Windows 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 timedeltaimport 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:
passtry:
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 = NoneCIP별로 국가별 ISO_Code가 추출됨을 알 수 있다.
'Python > Python for Windows' 카테고리의 다른 글
윈도우 2012 NTP 서버 구축 (2) - 서버 시간 모니터링 (0) 2019.08.07 python을 이용한 IIS web log 분석 (6) - 통계 분석 (0) 2019.07.23 python을 이용한 IIS web log 분석 (5) - DB화 (0) 2019.07.15 python을 이용한 IIS web log 분석 (4) - 파일 확장자 (0) 2019.07.15 윈도우 성능 데이터 분석 3부 - 사례를 이용한 grafana 시각화 (0) 2019.06.26 [Python] 디렉토리(하위포함) 파일명 점검 하기 (0) 2018.07.09 [Python] 변경된 날짜기준 파일검색 (0) 2018.06.17 [Python] 다수 파일에 원하는 문자열 찾기 (0) 2018.05.26