Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Is there a way to automatically geo-locate an ip-address on Ubuntu linux? I'm looking to do this for errors in my auth.log.

share|improve this question
    
What does "geo-locate an ip-address" mean? Look up where it comes from? –  womble Nov 20 '09 at 17:35
    
Find an approximate physical location associated with the ip address. –  C. Ross Nov 20 '09 at 17:39
add comment

3 Answers

up vote 3 down vote accepted

Ubuntu PreReqs:
sudo apt-get install libgeoip1 libgeo-ip-perl libregexp-common-perl

Script By Me just For you:

#Parses out ip and prints ip followed by country
use strict;
use warnings;

use Regexp::Common qw /net/;
use Geo::IP;

my $gi = Geo::IP->new(GEOIP_STANDARD);

while (<>) {
    #Following matches IPv4 addresses and stores the result in $1
    #The way this is now, it will only do the first IP on each line
    if (/($RE{net}{IPv4})/g) {
        print $1 . ':' . $gi->country_code_by_addr($1);
    }
}

Input Output:

65.19.146.2
65.19.146.2:US
65.19.146.2
220.248.0.0:CN

The script justs loops over its input, so if the script is called foo.pl and is executable, you can just do something like cat access.log | foo.pl. If you want more accurate detail, see Geo::IP perl module docs (and you might need to install a different database).

share|improve this answer
    
You will want the grep function mostly like for multiple matches on a line: perldoc.perl.org/functions/grep.html –  Kyle Brandt Nov 20 '09 at 19:23
    
Works great. Thanks a lot! –  C. Ross Nov 24 '09 at 17:39
add comment

It should be fairly straightforward in Perl. Just take auth.log and get a list of IPs out of it with grep or awk, then pipe your list of IPs into a Perl script, and use Geo::IP to get a country/city match from it.

share|improve this answer
add comment

From commandlinefu:

GeoipLookUp(){ curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.