A script to geo-locate ip addresses in auth.log

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.


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).


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.


From commandlinefu:

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