Playing with Python and GeoIP in Debian
Wednesday, October 14, 2009 - 11 commentsYep, I know, in the previous post I said that I'd try to write more often and in small chunks but looks like it's not working...
By the way, today I needed to find out the origin country of an hostname (actually a list of hostnames). As Debian has a GeoIP database available via aptitude, I could accomplish that using this database and the Python's GeoIP module.
First of all I installed the necessary packages
merlin:~# aptitude install geoip-database python-geoip
And then I wrote the following small script that configure the Python's GeoIP module to use the Debian's GeoIP database:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import GeoIP
# oops, check the usage! :)
if len(sys.argv) != 2:
print 'Usage: %s ADDRESS' % sys.argv[0]
sys.exit(1)
# geoip database from "geoip-database" debian package
GEOIP_DATABASE = '/usr/share/GeoIP/GeoIP.dat'
geoip = GeoIP.open(GEOIP_DATABASE, GeoIP.GEOIP_STANDARD)
# get the country name based in the given input
if re.match('^[0-9]{1,3}(\.[0-9]{1,3}){3}$', sys.argv[1]):
response = geoip.country_name_by_addr(sys.argv[1])
else:
response = geoip.country_name_by_name(sys.argv[1])
# print the response if there is any response
if response:
print response
Some tests to check if it is really working... and it looks like it is. :)
afurlan@merlin:~$ ./hostname_country.py afurlan.org
United States
afurlan@merlin:~$ ./hostname_country.py mandriva.com
France
afurlan@merlin:~$ ./hostname_country.py debian.com
Netherlands
afurlan@merlin:~$ ./hostname_country.py mps.com.br
Brazil
afurlan@merlin:~$ ./hostname_country.py some-nonexistent-domain.org
afurlan@merlin:~$
I think that's all...
Update: I changed the code based on the Bogdano's comment, thanks Bogdano. :)
And, please, never forget: if you found some english bug, warn me and I'll be glad to fix it. :)