Quelques mini-outils de plus…
[progfou.git] / outils / ip2cc
... / ...
CommitLineData
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Depends: python-geoip
4import sys
5import re
6try:
7 import GeoIP
8except:
9 print "Support GeoIP non disponible. Installer le paquet 'python-geoip'."
10 sys.exit(1)
11
12PATTERN_IP4 = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
13#REPLACEMENT_IP4 = '<%(cc)s>%(ip4)s'
14REPLACEMENT_IP4 = '<\033[1;31m%(cc)s\033[m>\033[34m%(ip4)s\033[m'
15
16gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
17
18def ip4_to_cc(matchobj):
19 ip4 = matchobj.group(0)
20 cc = gi.country_code_by_addr(ip4)
21 if cc is None: cc = '??'
22 return REPLACEMENT_IP4 % {'cc': cc, 'ip4': ip4}
23
24pattern = re.compile(PATTERN_IP4, re.MULTILINE)
25sys.stdout.write(re.sub(pattern, ip4_to_cc, sys.stdin.read()))