miércoles, marzo 22, 2006

Monitorizar un servidor con MRTG

MRTG es una herramienta con la que podemos monitorizar el tráfico de red, CPU, memoria, procesos/servicios, etc...


A continuación os adjunto una configuración válida para monitorizar la CPU, memoria consumida y libre, y los recursos de red.
También adjunto los scripts para poder monitorizar dichos valores. Lo cierto es que cada uno se puede hacer sus propios scripts, ya que es muy sencillo, pero para que todavía lo sea más, aquí adjunto los que yo uso.
Y como no, los pasos a realizar para instalarlo en un Linux, concretamente usando la distribución Debian (extremádamente sencillo)

NOTAS:
  1. Tendremos que editar el crontab para que cada 5 minutos haga un check automático de lo que queremos monitorizar
  2. Nuestro servidor web (Apache) lo tenemos configurado para que el root de la web sea /var/www/mrtg
  3. Los scripts los he colocado en /root/scripts/mrtg/
  4. Tendremos que, una vez creados los scripts, darles permisos de ejecución:
    1. ossim:~# chmod +x /root/scripts/mrtg/*
Empezamos... :
  • Instalación del paquete mrtg y atsar (para sacar datos que necesitamos):

ossim:~# apt-get install mrtg atsar
ossim:~# EDITOR=vi
ossim:~# export EDITOR
ossim:~# crontab -e
0-55/5 * * * * /usr/bin/mrtg /etc/mrtg.cfg
ossim:~#


  • Configuración del mrtg.cfg

ossim:~# cat /etc/mrtg.cfg

#RunAsDaemon: yes
EnableIPv6: no
WorkDir: /var/www/mrtg/

Options[_]: bits,growright
WriteExpires: Yes

Title[^]: Traffic Analysis for
######################################################################

###
### CPU info

###
Target[cpu]: `/root/scripts/mrtg/cpuinfo.sh`

MaxBytes[cpu]: 100
Options[cpu]: gauge, nopercent, nobanner, noinfo
YLegend[cpu]: % of CPU used
ShortLegend[cpu]: %
LegendO[cpu]: CPU User:
LegendI[cpu]: CPU System:
Title[cpu]: Cpu usage

Colours[cpu]: Rdeca#ff0000,Crna#000000,Temnozeleno#006600,Black#0015ff

Target[mem]: `/root/scripts/mrtg/meminfo.pl`
Options[mem]: gauge, noinfo, nobanner

Title[mem]: Memory Usage
MaxBytes[mem]: 928497664
YLegend[mem]: Memory
ShortLegend[mem]:
LegendO[mem]: Memory Free:
Legend2[mem]: Memory Free
LegendI[mem]: Memory Used:

Legend1[mem]: Memory Used
PageTop[mem]: Memory
Colours[mem]: Rdeca#ff0000,Crna#000000,Temnozeleno#006600,Black#0015ff

MaxBytes[eth0]: 104857600
AbsMax[eth0]: 104857600
Options[eth0]: noinfo
Target[eth0]: `/root/scripts/mrtg/ethinfo.pl -d eth0`
PageTop[eth0]: ETH0 - Traffic statistics
YLegend[eth0]: Bytes/s

ShortLegend[eth0]: B/s
Legend1[eth0]: Incoming Traffic
Legend2[eth0]: Outgoing Traffic
Legend3[eth0]: Maximum Incoming Traffic
Legend4[eth0]: Maximum Outgoing Traffic
LegendI[eth0]: In:

LegendO[eth0]: Out:
WithPeak[eth0]: ymwd

  • Creación del script para monitoritzar el consumo de CPU

ossim:~# vi scripts/mrtg/cpuinfo.sh

#!/bin/sh /usr/bin/atsar -u 1 3 | tail -n 1 | awk -F" " '{print $3"\n"$5}'

ossim:~#

  • Para acceder tenemos que abrir en el navegador la URL: http://IP_servidor_mrtg/mrtg/cpu.html
  • Script para monitoritzar la memoria RAM

ossim:~# cat /root/scripts/mrtg/meminfo.pl

#!/usr/bin/perl

$machine = `/bin/hostname`;
chomp($machine);
$mem = `/usr/bin/free | grep Mem`;
$uptime = `/usr/bin/uptime`;

if ($mem =~ /^Mem:\s*(\d*)\s*(\d*)\s*(\d*)/) {
$tot = $1 * 1024;
$used = $2 * 1024;
$free = $3 * 1024;
}

if ($uptime =~ /up (.*), \d* users?,/) {
$up = $1;
}
print "$used\n";
print "$free\n";
print "$up\n";
print "$machine\n";

ossim:~#



  • Creación del script para monitoritzar el consumo de red

#! /usr/bin/perl -w
# Modules
use strict;
use Getopt::Long;
###########################
# mrtg-eth.pl #
my $version="1.5.5"; #
# Mario Witte #
# mario.witte@chengfu.net #
###########################

################################################################################
# Configuration #
my $ssh="/usr/bin/ssh"; # Path to ssh #
my $ssh_opt="-o 'BatchMode yes' "; # ssh-Options #
$ssh_opt.="-o 'StrictHostKeyChecking no'";# #
my $devinfo="/proc/net/dev"; # Where to read device info from #
my $in_pos=0; # Position of bytes_in in $devinfo #
my $out_pos=8; # Position of bytes_out in $devinfo #
my $reverse=0; # reverse in/out bytes in output #
################################################################################

# Declare some variables
my $help=0;
my $helptext;
my $device;
my $remote_host;
my $identity_file;
my $remote_user;
my $remote_port;
my $ssh_protocol;
my %devinfo;

# Read Commandline parameters
&GetOptions( "device=s" => \$device,
"remotehost:s" => \$remote_host,
"identity:s" => \$identity_file,
"login:s" => \$remote_user,
"port:i" => \$remote_port,
"protocol:i" => \$ssh_protocol,
"pos_in:i" => \$in_pos,
"pos_out:i" => \$out_pos,
"t" => \$reverse,
"help" => \$help);

# Add for Slis
if (!$device) {
if ( -e "/etc/adsl" ){
$device = "ppp0";
} else {
$device = "eth0";
}
}

# If requested or no parameters given display help
if (!$device) { $help=1; $helptext=""; }

# Check if devicename is valid
if (($device) && ($device=~/^-/)) {
$help=1;
$helptext.="'$device' doesn't look like a device name\n";
} # end if $device

# Check if remotehost is valid
if (($remote_host) && ($remote_host=~/^-.{0,3}/)) {
$help=1;
$helptext.="'$remote_host' doesn't seem to be a hostname\n";
} # end if $remote

# Open help if requested/needed
if ($help==1) {
&help("$helptext");
exit;
}

if( $ssh_protocol ) {
if( $ssh_protocol == 1 or $ssh_protocol == 2 ) {
$ssh_opt .= " -$ssh_protocol";
}
}

if( $identity_file ) {
$ssh_opt .= " -i $identity_file";
$ENV{'SSH_AUTH_SOCK'} = '';
}

if( $remote_user ) {
$ssh_opt .= " -l $remote_user";
}

if( $remote_port ) {
$ssh_opt .= " -p $remote_port";
}

# Read statistics
if ($remote_host) { # remote host given, connect via ssh
my $ssh_cmd = "$ssh $ssh_opt $remote_host cat $devinfo";
open (DEV, "$ssh_cmd|");
} else { # read from localhost
open (DEV, "< $devinfo"); } map { @{$devinfo{$1}} = split /\s+/, $2 if( m/^\s*(.*):\s*(.*)$/); } ;
close DEV;

if (scalar keys %devinfo == 0) { &help("Could not read device info"); exit; }

if( ! defined $devinfo{$device} ) { &help("device $device not found"); exit; }

my $bytesin = $devinfo{$device}->[$in_pos];
my $bytesout = $devinfo{$device}->[$out_pos];

# Print Bytes per second to stdout
if ($reverse == 0) { print $bytesin . "\n"; }
print $bytesout . "\n";
if ($reverse == 1) { print $bytesin . "\n"; }

# Exit
exit;


# Subs
sub help($) {
if ($_[0]) { print "There were errors:\n $_[0]\n"; }
print "mrtg-eth.pl version $version - mario.witte\@chengfu.net\n";
print "\n";
print "Usage: mrtg-eth.pl -d device [-r host [-l login] [-i identity] [--port port] [--protocol 1|2]] [--pos_in n] [--pos_out n] [-t] [-b]\n";
print "\n";
print "Options:\n";
print "\t-d device - Device to be monitored (e.g. eth0, ippp1)\n";
print "\t-r host - If set, will try to connect to remote\n";
print "\t host via ssh (SSH)\n";
print "\t-l login - user on remote host (SSH)\n";
print "\t-i identity - use this private-key to connect to remote host (SSH)\n";
print "\t--protocol - use Protocol 1 or 2 to connect to remote host (SH)\n";
print "\t--port p - remote-sshd listens on port p (SSH)\n";
print "\t\n";
print "\t--pos_in n - Position of bytes_in in $devinfo\n";
print "\t--pos_out n - Position of bytes_out in $devinfo\n";
print "\t\n";
print "\t-t - reverse in/out bytes in output\n";
print "\n";
print "Options marked with '(SSH)' are only useful when connecting\n";
print "to a remote host using SSH\n";
print "\n";
} # end sub help

ossim:~#



Espero que con esto sea suficiente para que os funcione perfectamente dicha herramienta y podais tener un control de que tal trabaja vuestro servidor[es] todo el día.

-- La información es poder --