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.
Asked
Active
Viewed 3,505 times
2
-
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
4 Answers
4
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.

Tom O'Connor
- 27,480
- 10
- 73
- 148
4
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).

Kyle Brandt
- 83,619
- 74
- 305
- 448
-
You will want the grep function mostly like for multiple matches on a line: http://perldoc.perl.org/functions/grep.html – Kyle Brandt Nov 20 '09 at 19:23
-
Thats great. I would love to be able to get the output grouped by country, and #. Anyone can help? – weisk Jan 20 '17 at 01:01
1
From commandlinefu:
GeoipLookUp(){ curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; }

Dennis Williamson
- 62,149
- 16
- 116
- 151
0
with python:
sudo add-apt-repository ppa:maxmind/ppa
sudo apt update
sudo apt install libmaxminddb0 libmaxminddb-dev mmdb-bin
sudo pip install geoip2
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
tar xvfz GeoLite2-City.tar.gz
python -c 'import geoip2.database
reader = geoip2.database.Reader("./GeoLite2-City/GeoLite2-City.mmdb")
for line in open("/var/log/nginx/access.log').readlines():
response = reader.city(line.split(" ")[0])
print(dir(response))
'

jmunsch
- 123
- 5