Mi Blog
👉 Cómo monitorizar tu Raspberry Pi con MRTG

Cómo monitorizar tu Raspberry Pi con MRTG

 
(2 votos)

MRTG consiste en un script en Perl que utiliza SNMP (aunque no es obligatorio) para obtener información de gestión sobre los nodos de la red y un programa en C para generar los registros de tráfico (logs) y crear representaciones gráficas de los datos recopilados. Estos gráficos se integran dentro de un documento en formato HTML.

Seguid leyendo y os enseñaré de forma rápida como monitorizar vuestra Raspberry Pi con MRTG...

⬇️ Compra en Amazon el hardware que utilizo ⬇️

🔥 ¡DESCÚBRELOS! 🔥

 

 

¿QUÉ ES MRTG?

MRTG (Multi Router Traffic Grapher) es una herramienta de código abierto utilizada para monitorizar el tráfico de red, y es una de las herramientas de monitoreo más populares y ampliamente utilizadas. Es una herramienta basada en web, lo que significa que se ejecuta en un servidor web que hace posible que los usuarios accedan al software a través de un navegador web. MRTG utiliza SNMP (Simple Network Management Protocol) para recopilar información de los dispositivos de la red y luego genera gráficos que muestran la utilización de la red en tiempo real, aunque no es necesario SNMP. La información se presenta en forma de gráficos que muestran el uso de la red en una variedad de formatos, como tablas y gráficos de barras. MRTG es una herramienta muy eficaz para monitorear el ancho de banda de la red y la utilización de los servidores y dispositivos de red, lo que es esencial para garantizar un rendimiento óptimo del sistema y reducir el tiempo de inactividad de los servicios críticos.

 

 

MRTG monitoriza tanto el tráfico de red como los recursos de dispositivos en tiempo real.

 

 

1.- ELEMENTOS NECESARIOS PARA ESTE TUTORIAL

  • Una Raspberry Pi con OSMC/Raspbian o similar
  • Conexión a Internet

 

 

2.- ELEMENTOS A MONITORIZAR

En el siguiente tutorial vamos a prender a monitorizar los siguientes elementos de una vieja Raspberry Pi 1 B+ y además, SIN UTILIZAR SNMP.

  • CPU Load: Carga de CPU (hace 5 y 15 mins)
  • CPU Temperature: Temperatura de la CPU
  • Memory Usage: Uso de memoria RAM
  • LAN Traffic Analysis: Tráfico de red ethernet
  • Root FS 16GB Free GB: Espacio libre en GB de la SD-Card del Sistema Operativo
  • USB128GB FS Free GB: Espacio libre en GB de un USB de 128GB para servidor DLNA
  • Root FS 16GB Usage %: Porcentaje ocupado en % de la SD-Card del Sistema Operativo
  • USB128GB FS Usage %: Porcentaje ocupado en % de un USB de 128GB para ervidor DLNA
  • Number of users: Usuarios en el sistema
  • Total of running applications: Procesos funcionando
  • Ping Google: Tiempo en ms a Google

 

 

 

 

3.- INSTALACIÓN DE MRTG

Para instalar MRTG es tan sencillo como actualizar la lista de paquetes de nuestro repositorio de Debian y lanzar la instalación de MRTG con los 2 comandos siguientes:

osmc@osmc:~$ sudo apt-get update
osmc@osmc:~$ sudo apt-get install mrtg

 

 

4.- INSTALAR HERRAMIENTAS AUXILIARES

Para extraer la información de la Raspberry Pi y poder mostrar los datos, se necesitan de una serie de comandos extras que no vienen -generalmente- por defecto en GNU/Linux. Para ello debemos instalar los paquetes necesarios con el siguiente comando:

osmc@osmc:~$ sudo apt-get install bc ifstat

 

 

5.- CONFIGURAR MRTG

 Editaremos el fichero de configuración principal de MRTG /etc/mrtg/mrtg.cfg y añadiremos el siguiente contenido:

LogDir: /var/log/mrtg
HtmlDir: /var/www/mrtg
ImageDir: /var/www/mrtg
Title[_]: "Raspberry Pi Stats"
Colours[_]: LIGHT BLUE#6699FF,BLUE#1000ff,DARK BLUE#000066,VIOLET#ff00ff,GREEN##00ff00
Background[_]: #ffffff
#RunAsDaemon: Yes
Interval: 5

XSize[_]: 300
YSize[_]: 100
Timezone[_]: Europe/Madrid
TimeStrPos[_]: RU
TimeStrFmt[_]: %a %d %b %H:%M %Y
PageFoot[_]: When you have questions contact: <A HREF="mailto:raul.lnxATgmail.com">RPF</A>
SnmpOptions: timeout => 10
Suppress[_]: y

XZoom[_]: 1.4
YZoom[_]: 1.4
XScale[_]: 1.2
YScale[_]: 1.2

Include: /etc/mrtg/raspi.inc

 

 

5.1.- GRÁFICA DE CARGA DE CPU

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# CPU Load
Title[raspi1-CPU]: CPU Load
PageTop[raspi1-CPU]: <H1>CPU Load</H1>
MaxBytes[raspi1-CPU]: 10000
ShortLegend[raspi1-CPU]: %
YLegend[raspi1-CPU]: CPU %
Legend1[raspi1-CPU]: Load Average 1 min
Legend2[raspi1-CPU]: Load Average 5 min
LegendI[raspi1-CPU]: Load Average 1 min
LegendO[raspi1-CPU]: Load Average 5 min
Target[raspi1-CPU]: `bash /etc/mrtg/cpuload.sh`
Options[raspi1-CPU]: integer,growright,nopercent,gauge
Colours[raspi1-CPU]:GREEN#00eb0c,BLUE#1000ff,DARK GREEN#006600,VIOLET#ff00ff

 

 

Y crearemos el script de bash /etc/mrtg/cpuload.sh con el siguiente contenido:

#!/bin/bash
CPU1=`uptime | sed 's/.*load average: //' | awk -F\, '{print $1}'`
CPU2=`uptime | sed 's/.*load average: //' | awk -F\, '{print $3}'`
echo "$CPU1 * 100" | bc ;
echo "$CPU2 * 100" | bc ;

 

  

5.2.- GRÁFICA DE TEMPERATURA DE CPU

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# CPU Temperature
Title[raspi1-CPU-temp]: CPU Temperature
PageTop[raspi1-CPU-temp]: <H1>CPU Temperature</H1>
MaxBytes[raspi1-CPU-temp]: 120
ShortLegend[raspi1-CPU-temp]: Celsius
YLegend[raspi1-CPU-temp]: Celsius
Legend1[raspi1-CPU-temp]: Celsius
LegendI[raspi1-CPU-temp]: Celsius
LegendO[raspi1-CPU-temp]: Celsius
Target[raspi1-CPU-temp]: `bash /etc/mrtg/cputemp.sh`
Options[raspi1-CPU-temp]: integer,growright,nopercent,gauge,noo
Colours[raspi1-CPU-temp]: ORANGE#f75712,G#04bf27,G#70ff53,R#70ff53

 

 

Y crearemos el script de bash /etc/mrtg/cputemp.sh con el siguiente contenido:

#!/bin/bash
TEMP=`cat /sys/class/thermal/thermal_zone0/temp`
echo "$TEMP * 0.001" | bc ;
echo "$TEMP * 0.001" | bc ;

 

 

5.3.- GRÁFICA DE USO DE MEMORIA RAM

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Memory
Title[raspi1-mem]: Memory Usage
PageTop[raspi1-mem]: <H1>Memory Usage</H1>
MaxBytes[raspi1-mem]: 370
kmg[raspi1-mem]: MB
kilo[raspi1-mem]: 1024
ShortLegend[raspi1-mem]:
YLegend[raspi1-mem]: Memory MB
Legend1[raspi1-mem]: Memory used
Legend2[raspi1-mem]: Memory available
LegendI[raspi1-mem]: Memory used
LegendO[raspi1-mem]: Memory available
Target[raspi1-mem]: `bash /etc/mrtg/memusage.sh`
Options[raspi1-mem]: integer,growright,nopercent,gauge
Unscaled[raspi1-mem]: ymwd
AbsMax[raspi1-mem]: 370
Colours[raspi1-mem]: DIRTY YELLOW#E6B420,ORANGE#E65120,THIRD#993615,FOURTH#997815

 

 

Y crearemos el script de bash /etc/mrtg/memusage.sh con el siguiente contenido:

#!/bin/bash
MEM1=`free | grep Mem | awk '{print $3}'` #used
MEM2=`free | grep Mem | awk '{print $7}'` #available
echo "$MEM1 / 1024" | bc;
echo "$MEM2 / 1024" | bc;

 

 

5.4.- GRÁFICA DE USO DE RED

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Network Traffic
Title[raspi1-networktraffic]: Traffic Eth0
PageTop[raspi1-networktraffic]: <H1>LAN Traffic Analysis</H1>
Target[raspi1-networktraffic]: `bash /etc/mrtg/iface_speed.sh`
MaxBytes[raspi1-networktraffic]: 100
kmg[raspi1-networktraffic]: M
ShortLegend[raspi1-networktraffic]: bps
YLegend[raspi1-networktraffic]: Net.Speed (mbps)
Legend1[raspi1-networktraffic]: Upload (mbps)
Legend2[raspi1-networktraffic]: Download (mbps)
LegendI[raspi1-networktraffic]: Upload (mbps)
LegendO[raspi1-networktraffic]: Download (mbps)
Options[raspi1-networktraffic]: integer,unknaszero,nopercent,gauge,growright,withzeroes
#Unscaled[raspi1-networktraffic]: ymwd
AbsMax[raspi1-networktraffic]: 100

 

 

Y crearemos el script de bash /etc/mrtg/iface_speed.sh con el siguiente contenido:

#!/bin/bash
SPEED=`ifstat -b 1 3 | tail -n 1`
SPEED_DOWN=`echo $SPEED | awk '{print $1}'`
SPEED_UP=`echo $SPEED | awk '{print $NF}'`
echo "scale=2; $SPEED_DOWN / 1000" | bc -l | sed 's/^\./0./';
echo "scale=2; $SPEED_UP / 1000" | bc -l | sed 's/^\./0./';

 

 

5.5.- GRÁFICA DE ESPACIO LIBRE EN LA TARJETA SD EN GB

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Monitor root FS 16GB
Title[localhost.rootfsfree]: Root FS 16GB Free GB
PageTop[localhost.rootfsfree]: <H1>Root FS 16GB Free GB</H1>
MaxBytes[localhost.rootfsfree]: 16
kmg[localhost.rootfsfree]: GB
kilo[localhost.rootfsfree]: 1024
ShortLegend[localhost.rootfsfree]:
YLegend[localhost.rootfsfree]: Free BG /
LegendI[localhost.rootfsfree]: Root FS 16GB Free BG
Target[localhost.rootfsfree]: `bash /etc/mrtg/rootfilesystembysize.sh`
Options[localhost.rootfsfree]: integer,growright,nopercent,gauge,noo
Unscaled[localhost.rootfsfree]: ymwd
#Factor[localhost.rootfsfree]: 0.001
AbsMax[localhost.rootfsfree]: 16
Colours[localhost.rootfsfree]: LIGHT GREEN#40E0D0,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/rootfilesystembysize.sh con el siguiente contenido:

#!/bin/bash
FREE=`df / | grep "/" | awk '{print $4}' | cut -d "%" -f1`
echo "scale=2; $FREE / 1024 / 1024" | bc -l;
echo "scale=2; $FREE / 1024 / 1024" | bc -l;

 

 

5.6.- GRÁFICA DE ESPACIO LIBRE EN USB128GB EN GB

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Monitor /media/USB128GB FS
Title[localhost.usb128gbfsfree]: USB128GB FS Free GB
PageTop[localhost.usb128gbfsfree]: <H1>USB128GB FS Free GB</H1>
MaxBytes[localhost.usb128gbfsfree]: 128
kmg[localhost.usb128gbfsfree]: GB
kilo[localhost.usb128gbfsfree]: 1024
ShortLegend[localhost.usb128gbfsfree]:
YLegend[localhost.usb128gbfsfree]: Free GB USB128GB
LegendI[localhost.usb128gbfsfree]: USB128GB FS Free GB
Target[localhost.usb128gbfsfree]: `bash /etc/mrtg/128gbfilesystembysize.sh`
Options[localhost.usb128gbfsfree]: integer,growright,nopercent,gauge,noo
Unscaled[localhost.usb128gbfsfree]: ymwd
#Factor[localhost.usb128gbfsfree]: 0.001
AbsMax[localhost.usb128gbfsfree]: 128
Colours[localhost.usb128gbfsfree]: LIGHT GREEN#40E0D0,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/128gbfilesystembysize.sh con el siguiente contenido:

#!/bin/bash
FREE=`df /media/USB128GB | grep "/" | awk '{print $4}' | cut -d "%" -f1`
echo "scale=2; $FREE / 1024 / 1024" | bc -l;
echo "scale=2; $FREE / 1024 / 1024" | bc -l;

 

 

5.7.- GRÁFICA DE USO DE LA TARJETA SD EN %

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Monitor root FS 16GB %
Title[localhost.rootfs]: Root FS 16GB Usage %
PageTop[localhost.rootfs]: <H1>Root FS 16GB Usage %</H1>
MaxBytes[localhost.rootfs]: 100
ShortLegend[localhost.rootfs]: %
YLegend[localhost.rootfs]: % /
LegendI[localhost.rootfs]: Root FS 16GB Usage %:
Target[localhost.rootfs]: `bash /etc/mrtg/rootfilesystem.sh`
Options[localhost.rootfs]: integer,growright,gauge,noo
Unscaled[localhost.rootfs]: ymwd
AbsMax[localhost.rootfs]: 100
Colours[localhost.rootfs]: CRISMON#DE3163,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/rootfilesystem.sh con el siguiente contenido:

#!/bin/bash
USAGE=`df -h / | grep "/" | awk '{print $5}' | cut -d "%" -f1`
echo "$USAGE";
echo "$USAGE";

 

 

5.8.- GRÁFICA DE USO DEL USB128GB EN %

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Monitor /media/USB128GB %
Title[localhost.usb128gb]: USB128GB FS Usage %
Target[localhost.usb128gb]: `bash /etc/mrtg/128gbfilesystem.sh`
PageTop[localhost.usb128gb]: <H1>USB128GB FS Usage %</H1>
MaxBytes[localhost.usb128gb]: 100
ShortLegend[localhost.usb128gb]: %
YLegend[localhost.usb128gb]: % USB128GB
LegendI[localhost.usb128gb]: USB128GB FS Usage %:
Options[localhost.usb128gb]: integer,growright,gauge,noo
Unscaled[localhost.usb128gb]: ymwd
AbsMax[localhost.usb128gb]: 100
Colours[localhost.usb128gb]: CRISMON#DE3163,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/128gbfilesystem.sh con el siguiente contenido:

#!/bin/bash
USAGE=`df -h /media/USB128GB/ | grep "/" | awk '{print $5}' | cut -d "%" -f1`
echo "$USAGE";
echo "$USAGE";

 

 

5.9.- GRÁFICA DE USUARIOS EN EL SISTEMA

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Get Number of Current sers
Title[localhost.users]: Logged in Users
Target[localhost.users]: `bash /etc/mrtg/linux_users.sh`
PageTop[localhost.users]: <H1>Number of Users</H1>
MaxBytes[localhost.users]: 100000
ShortLegend[localhost.users]: Users
kMG[localhost.users]: ,
YLegend[localhost.users]: users count
Options[localhost.users]: integer,nopercent,growright,unknaszero,nopercent,gauge,withzeroes,noo
Colours[localhost.users]: RED#FF0000,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/linux_users.sh con el siguiente contenido:

#!/bin/bash
USERS=`who | wc -l`
echo "$USERS";
echo "$USERS";

 

 

5.10.- GRÁFICA DE TOTAL PROCESOS FUNCIONANDO

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Total of running applications
Title[count-apps]: Applications
Target[count-apps]: `bash /etc/mrtg/count_apps.sh`
MaxBytes[count-apps]: 1000
#AbsMax[count-apps]: 10000
kMG[count-apps]: ,
YLegend[count-apps]: Total
ShortLegend[count-apps]: App's
LegendO[count-apps]: Total:
PageTop[count-apps]: <H1>Total of running applications</H1>
WithPeak[count-apps]: wmy
Options[count-apps]: integer,growright,unknaszero,nopercent,gauge,withzeroes,noo
Colours[count-apps]: BLACK#696969,SECOND#000000,THIRD#000000,FOURTH#000000

 

 

Y crearemos el script de bash /etc/mrtg/count_apps.sh con el siguiente contenido:

#!/bin/sh
O=$(/bin/ps wwwax | grep "$1" | grep -v grep | wc -l)
echo $O
echo $O

 

 

5.11.- GRÁFICA DE PING A GOOGLE

En el fichero /etc/mrtg/raspbi.inc debemos añadir lo siguiente: 

# Ping Google
Title[raspi1-ping]: Ping Google
PageTop[raspi1-ping]: <H1>Ping Google</H1>
MaxBytes[raspi1-ping]: 10000000
ShortLegend[raspi1-ping]: ms
YLegend[raspi1-ping]: Ping Google (ms)
Legend1[raspi1-ping]: Ping (ms)
LegendI[raspi1-ping]: Ping (ms)
Target[raspi1-ping]: `bash /etc/mrtg/pinginternet.sh`
Factor[raspi1-ping]: 0.001
Options[raspi1-ping]: integer,growright,nopercent,gauge,noo
Colours[raspi1-ping]: VIOLETE#9B59B6,BLUE#1000ff,DARK GREEN#006600,VIOLET#ff00ff

 

 

Y crearemos el script de bash /etc/mrtg/pinginternet.sh con el siguiente contenido:

#!/bin/bash
STATS=`ping -c 3 8.8.8.8 | grep round-trip | awk '{print $4}'`
PING=`echo $STATS | awk -F "/" '{print $2}'`
echo "$PING";
echo "$PING";

 

  

6.- GENERAR EL INDEX.HTML

Para generar la web index.html de MRTG de forma automática debemos ejecutar el siguiente comando, indicando el fichero de configuración y donde queremos dejar el fichero index.html:

osmc@osmc:~$ sudo indexmaker --output=/var/www/mrtg/index.html /etc/mrtg/mrtg.cfg

 

 

7.- CRONTAB

Por último, debemos añadir en el programador de tareas CRON del usuario root, la ejecución de MRTG cada 5 minutos para ir recolectando la información. Para ello, ejecutaremos crontab con el comando siguiente:

osmc@osmc:~$ sudo crontab -e

 

 

Y añadiremos al final, la siguiente línea;

*/5 * * * * /usr/bin/mrtg /etc/mrtg/mrtg.cfg

 

 

8.- ACCESO A MRTG

Para acceder a MRTG (a su página principal) y si hemos instalado Apache2 correctamente, deberemos acceder a través del navegador y su URL por defecto. En este ejemplo la URL utilizada ha sido http://192.168.1.2/mrtg/:

Monitorizar Raspberry PI con MRTGMRTG Raspberry Pi

 

 

ENJOY!