Plugin GeoIP Awstats

De EjnTricks

Le plugin GeoIP va permettre de donner une correspondance entre les adresses IP et le pays où se situe la machine. Cela est un peu gadget, mais il est toujours amusant de tracer un peu qui vient voir le site.

Les informations de localisation sont récupérables à partir de MaxMind.

Hand-icon.png Votre avis

Current user rating: 97/100 (5 votes)

 You need to enable JavaScript to vote


System-Install-icon.png Installation

Download-icon.png Récupération informations de localisation

La première étape consiste à récupérer la base des adresses IP, depuis le MaxMind. Le fichier doit être téléchargé dans le répertoire /usr/share/awstats/plugins/.

#sudo wget -P /usr/share/awstats/plugins/ http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
--2012-03-02 00:20:55--  http://www.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
Résolution de www.maxmind.com... 208.43.124.51
Connexion vers www.maxmind.com|208.43.124.51|:80... connecté.
requête HTTP transmise, en attente de la réponse... 301 Moved Permanently
Emplacement: http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz [suivant]
--2012-03-02 00:20:55--  http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
Résolution de geolite.maxmind.com... 174.36.207.186
Connexion vers geolite.maxmind.com|174.36.207.186|:80... connecté.
requête HTTP transmise, en attente de la réponse... 200 OK
Longueur: 703282 (687K) [text/plain]
Sauvegarde en : «/usr/share/awstats/plugins/GeoIP.dat.gz»

100%[=============================================================================================>] 703 282      458K/s   ds 1,5s

2012-03-02 00:20:57 (458 KB/s) - «/usr/share/awstats/plugins/GeoIP.dat.gz» sauvegardé [703282/703282]

Une fois téléchargé, il faut le décompresser à l'aide de l'outil gunzip.

cd /usr/share/awstats/plugins
#sudo gunzip GeoIP.dat.gz

Scheduled-Tasks-icon.png Planification des informations de localisation

MaxMind publie les informations de localisation mensuellement. Afin d'éviter de penser à les mettre à jour manuellement, il est préférable de planifier le télécharger à l'aide de Crontab ou Anacron. L'outil Crontab va être utilisé dans ce cas, afin de spécifier un jour particulier dans le mois, soit le 3ème.

Les scripts suivants sont inspirés de l'article: http://blog.pastoutafait.org/billets/Installation-et-configuration-de-AwStats-sur-Debian-Squeeze

La première étape consiste en la création du fichier de download.

#sudo mkdir /var/opt/awstats
#sudo touch /var/opt/awstats/download_geoip.sh
#sudo chmod 750 /var/opt/awstats/download_geoip.sh

Le contenu du script download_geoip.sh permet de supprimer le fichier actuel, et de télécharger la nouvelle version.

#!/bin/bash
LOCALPATH=/usr/share/awstats/plugins/

if [ -f $LOCALPATH"GeoIP.dat.gz" ]; then 
	rm -f $LOCALPATH"GeoIP.dat.gz"
fi

/usr/bin/wget -q --output-document=$LOCALPATH"GeoIP.dat.gz" http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip -f $LOCALPATH"GeoIP.dat.gz"

Une fois le script créé, il faut le planifier dans Crontab. Dans le cadre de cette utilisation, il sera exécuté tous les troisième jours du mois à 5h30 du matin. La planification est donc la suivante:

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
30 5    3 * *   root    cd / && /var/opt/awstats/download_geoip.sh > /dev/null
#

Attention, un nombre maximum de demande d'accès est autorisé par jour. Il ne faut pas essayer de demander trop souvent les bases de données au risque de recevoir temporairement une erreur 403.

Share-icon.png Mutualisation

Si les informations de localisation peuvent être utiles pour d'autre application, comme piwik, il est nécessaire de centraliser la mise en place de ces fichiers. Elles seront téléchargées dans le répertoire /var/datas/maxmind. La mise en place de cette mutualisation s'effectue à l'aide des étapes suivantes:

  • Création du répertoire de téléchargement /var/datas/maxmind.
#sudo mkdir /var/datas/maxmind
#sudo chown www-data:www-data /var/datas/maxmind
#sudo chmod 750 /var/datas/maxmind
  • Création du script pour la tâche planifiée à l'emplacement /var/opt/geo/download_geoip.sh.
#sudo mkdir /var/opt/geo
#sudo chown www-data:www-data /var/opt/geo
#sudo chmod 750 /var/opt/geo

Et le contenu du script est:

#!/bin/bash
LOCALPATH=/var/datas/maxmind/
DOWN_FILE=$LOCALPATH"GeoIp.dat.gz"

if [ -f $DOWN_FILE ]; then
        rm -f $DOWN_FILE
fi

/usr/bin/wget -q --output-document=$DOWN_FILE http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip -f $DOWN_FILE


  • Modification de la crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
30 5    3 * *   root    cd / && /var/opt/geo/download_geoip.sh > /dev/null
#

Installation extension PurePerl.pm

Afin de pouvoir utiliser les données, il est nécessaire de récupérer le script PurePerl.pm, toujours sur le site MaxMind, à l'adresse http://geolite.maxmind.com/download/geoip/api/pureperl/ La version 1.25 est récupérée.

#sudo wget -P /tmp http://geolite.maxmind.com/download/geoip/api/pureperl/Geo-IP-PurePerl-1.25.tar.gz 
--2012-03-02 00:26:30--  http://geolite.maxmind.com/download/geoip/api/pureperl/Geo-IP-PurePerl-1.25.tar.gz
Résolution de geolite.maxmind.com... 174.36.207.186
Connexion vers geolite.maxmind.com|174.36.207.186|:80... connecté.
requête HTTP transmise, en attente de la réponse... 200 OK
Longueur: 21674 (21K) [text/plain]
Sauvegarde en : «/tmp/Geo-IP-PurePerl-1.25.tar.gz»

100%[=============================================================================================>] 21 674      98,3K/s   ds 0,2s

2012-03-02 00:26:31 (98,3 KB/s) - «/tmp/Geo-IP-PurePerl-1.25.tar.gz» sauvegardé [21674/21674]

Le fichier est alors disponible dans /tmp. Il faut le décompresser, avec la commande tar, dans le répertoire /usr/share/awstats/lib/.

#sudo tar -C /usr/share/awstats/lib -xzvf /tmp/Geo-IP-PurePerl-1.25.tar.gz
Geo-IP-PurePerl-1.25/
Geo-IP-PurePerl-1.25/Changes
Geo-IP-PurePerl-1.25/COPYING
Geo-IP-PurePerl-1.25/geoip-lookup
Geo-IP-PurePerl-1.25/geoip-lookup-city
Geo-IP-PurePerl-1.25/geoip-lookup-isp
Geo-IP-PurePerl-1.25/geoip-lookup-netspeed
Geo-IP-PurePerl-1.25/geoip-lookup-org
Geo-IP-PurePerl-1.25/geoip-lookup-region
Geo-IP-PurePerl-1.25/INSTALL
Geo-IP-PurePerl-1.25/lib/
Geo-IP-PurePerl-1.25/lib/Geo/
Geo-IP-PurePerl-1.25/lib/Geo/IP/
Geo-IP-PurePerl-1.25/lib/Geo/IP/PurePerl.pm
Geo-IP-PurePerl-1.25/Makefile.PL
Geo-IP-PurePerl-1.25/MANIFEST
Geo-IP-PurePerl-1.25/META.yml
Geo-IP-PurePerl-1.25/README
Geo-IP-PurePerl-1.25/t/
Geo-IP-PurePerl-1.25/t/0_base.t
Geo-IP-PurePerl-1.25/t/1_lookup.t
Geo-IP-PurePerl-1.25/t/2_namelookup.t

#sudo chown -R root /usr/share/awstats/lib/Geo-IP-PurePerl-1.25/


Icon-Configuration-Settings.png Paramétrage

Modification extension PurePerl.pm

Une fois installée, il est nécessaire de modifier le script PurePerl.pm, qui se trouve alors dans le répertoire /usr/share/awstats/lib/Geo-IP-PurePerl-1.25/lib/Geo/IP. La modification consiste à modifier l'emplacement de la base GeoIp, soit le fichier /usr/share/awstats/plugins/GeoIP.dat, dans la fonction sub new .

sub new {
  my ($class, $db_file, $flags) = @_;
  # this will be less messy once deprecated new( $path, [$flags] )
  # is no longer supported (that's what open() is for)

  #my $def_db_file = '/usr/local/share/GeoIP/GeoIP.dat';
  my $def_db_file = '/usr/share/awstats/plugins/GeoIP.dat';
    if ($^O eq 'NetWare') {
    $def_db_file = 'sys:/etc/GeoIP/GeoIP.dat';
  } elsif ($^O eq 'MSWin32') {
    $def_db_file = 'c:/GeoIP/GeoIP.dat';
  }
  if ( !defined $db_file ) {
    # called as new()
    $db_file = $def_db_file;
  } elsif ( $db_file =~ /^\d+$/ ) {
    # db_file is GEOIP_MEMORY_CACHE or GEOIP_STANDARD
    # called as new( $flags )
    $flags = $db_file;
    $db_file = $def_db_file;
  } # else called as new( $database_filename, [$flags] );

  $class->open( $db_file, $flags );
}

A noter qu'il serait aussi possible de placer ce fichier à l'emplacement /usr/local/share/GeoIP/GeoIP.dat.

Le script PurePerl.pm doit être ensuite copié dans le répertoire lib de Awstats, à savoir /usr/share/awstats/lib/.

#sudo cp /usr/share/awstats/lib/Geo-IP-PurePerl-1.25/lib/Geo/IP/PurePerl.pm /usr/share/awstats/lib/

Modification script geoip.pm

L'étape suivante va permettre de modifier le comportement de Awstats afin de prendre en compte cette nouvelle extension. Il faut modifier le fichier geoip.pm dans le répertoire des plugins de Awstats, soit /usr/share/awstats/plugins, afin de référencer l'emplacement du script PurePerl.pm.

use vars qw/ $type /;
$type='geoip';
if (!eval ('require "Geo/IP.pm";')) {
        $error1=$@;
        $type='geoippureperl';
        #if (!eval ('require "Geo/IP/PurePerl.pm";')) {
        if (!eval ('require "/usr/share/awstats/lib/PurePerl.pm";')) {
                $error2=$@;
                $ret=($error1||$error2)?"Error:\n$error1$error2":"";
                $ret.="Error: Need Perl module Geo::IP or Geo::IP::PurePerl";
                return $ret;
        }
}
# ----->
#use strict;
no strict "refs";

Attention, avec la mise à jour de Unbuntu en version 12.04 LTS, Awstats est mis à jour et les modifications faites sont perdues. Lors du calcul des statistiques, le message suivant est affiché:

Error: Plugin load for plugin 'geoip' failed with return code: Error:
Can't locate Geo/IP.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . 
/usr/share/awstats/lib /usr/share/awstats/plugins) at (eval 3) line 1.
Can't locate Geo/IP/PurePerl.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . 
/usr/share/awstats/lib /usr/share/awstats/plugins) at (eval 4) line 1.
Error: Need Perl module Geo::IP or Geo::IP::PurePerl
Setup ('/etc/awstats/awstats.www.jouvinio.net.conf' file, web server or permissions) may be wrong.
Check config file, permissions and AWStats documentation (in 'docs' directory).
Error: Plugin load for plugin 'geoip' failed with return code: Error:
Can't locate Geo/IP.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 /usr/lib/perl5 
/usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . /usr/share/awstats/lib 
/usr/share/awstats/plugins) 
at (eval 3) line 1.
Can't locate Geo/IP/PurePerl.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . 
/usr/share/awstats/lib /usr/share/awstats/plugins) 
at (eval 4) line 1.
Error: Need Perl module Geo::IP or Geo::IP::PurePerl
Setup ('/etc/awstats/awstats.www.dev.jouvinio.net.conf' file, web server or permissions) may be wrong.
Check config file, permissions and AWStats documentation (in 'docs' directory).

Afin de résoudre ce problème, la première modification consiste à mettre en place un lien sur Geo-IP-PurePerl-1.25/lib/Geo dans /usr/share/awstats/lib.

#cd /usr/share/awstats/lib
#ln -s Geo-IP-PurePerl-1.25/lib/Geo Geo

Le calcul s'effectue alors correctement, mais l'application produit toujours une erreur.


Le message présenté indique que la solution choisi n'est pas optimale.

Error: Plugin load for plugin 'geoip_city_maxmind' failed with return code: 
Error: Can't locate Geo/IP.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . 
/usr/share/awstats/plugins) at (eval 3) line 1. 
Can't locate Geo/IP/PurePerl.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . /usr/share/awstats/plugins)
at (eval 4) line 1.
Error: Need Perl module Geo::IP or Geo::IP::PurePerl 

En effet, le lien a été mis en place dans le répertoire lib qui n'est pas pris en compte lors de la visualisation. Le lien est donc mis en place dans le répertoire plugins.

#sudo rm /usr/share/awstats/lib/Geo
#cd /usr/share/awstats/plugins
#ln -s ../lib/Geo-IP-PurePerl-1.25/lib/Geo Geo

Modification paramétrage awstats

Enfin, il faut modifier la configuration de statistique sur le site. Dans le cadre de cet article, la configuration se situe dans le fichier /etc/awstats/awstats.www.jouvinio.net.conf. L'objectif est de référencer le nouveau plugin en modifiant le paramétrage LoadPlugin. La première modification serait la suivante:

# PLUGIN: GeoIP
# REQUIRED MODULES: Geo::IP or Geo::IP::PurePerl (from Maxmind)
# PARAMETERS: [GEOIP_STANDARD | GEOIP_MEMORY_CACHE] [/pathto/geoip.dat[+/pathto/override.txt]]
# DESCRIPTION: Builds a country chart and adds an entry to the hosts
# table with country name
# Replace spaces in the path of geoip data file with string "%20".
#
#LoadPlugin="geoip GEOIP_STANDARD /usr/share/GeoIP/GeoIP.dat"
LoadPlugin="geoip GEOIP_STANDARD /usr/share/awstats/plugins/GeoIP.dat"

Une configuration est déjà mise à disposition, mais avec un emplacement de la base différent. C'est pourquoi la configuration est recopiée mais modifiée.

Mutualisation des informations de localisation

Dans le cas de mutualisation décrit précédemment, la modification du script PurePerl.pm est la suivante:

sub new {
  my ($class, $db_file, $flags) = @_;
  # this will be less messy once deprecated new( $path, [$flags] )
  # is no longer supported (that's what open() is for)

  #my $def_db_file = '/usr/local/share/GeoIP/GeoIP.dat';
  my $def_db_file = '/var/datas/maxmind/GeoIP.dat';
    if ($^O eq 'NetWare') {
    $def_db_file = 'sys:/etc/GeoIP/GeoIP.dat';
  } elsif ($^O eq 'MSWin32') {
    $def_db_file = 'c:/GeoIP/GeoIP.dat';
  }
  if ( !defined $db_file ) {
    # called as new()
    $db_file = $def_db_file;
  } elsif ( $db_file =~ /^\d+$/ ) {
    # db_file is GEOIP_MEMORY_CACHE or GEOIP_STANDARD
    # called as new( $flags )
    $flags = $db_file;
    $db_file = $def_db_file;
  } # else called as new( $database_filename, [$flags] );

  $class->open( $db_file, $flags );
}

Il faut également modifier le fichier de configuration /etc/awstats/awstats.www.jouvinio.net.conf pour pointer sur le bon emplacement:

# PLUGIN: GeoIP
# REQUIRED MODULES: Geo::IP or Geo::IP::PurePerl (from Maxmind)
# PARAMETERS: [GEOIP_STANDARD | GEOIP_MEMORY_CACHE] [/pathto/geoip.dat[+/pathto/override.txt]]
# DESCRIPTION: Builds a country chart and adds an entry to the hosts
# table with country name
# Replace spaces in the path of geoip data file with string "%20".
#
#LoadPlugin="geoip GEOIP_STANDARD /usr/share/GeoIP/GeoIP.dat"
LoadPlugin="geoip GEOIP_STANDARD /var/datas/maxmind/GeoIP.dat"


Viewer icon.png Rendu

Une fois l'extension installée, le pays est affichée sur certains rapports, donnant l'indication de l'emplacement de l'adresse IP.