Capítulo 11.3 - Monitoreo de Crons y Alertas
Objetivos de Aprendizaje
Al final de este capítulo, usted será capaz de:
- Monitorear la ejecución de crons
- Detectar fallos de tareas
- Configurar alertas para crons
- Notificar por email/Slack
- Crear dashboards de monitoreo
- Implementar health checks
Monitoreo de Crons
Verificar Ejecución
# Ver últimas ejecuciones
sudo grep CRON /var/log/syslog | tail -20
# Por script
sudo grep "mon-script.sh" /var/log/syslog
# journalctl
sudo journalctl -u cron --since "1 hour ago"
# Verificar si se ejecutó hoy
sudo grep "mon-script.sh" /var/log/syslog | grep "$(date +%b\ %d)"
Script de Verificación
#!/bin/bash
# Verificar ejecución cron
SCRIPT="mon-script.sh"
LOG="/var/log/syslog"
EXPECTED_TIME="02:00" # Hora esperada
# Verificar ejecución hoy
TODAY=$(date +%b\ %d)
EXECUTED=$(grep "$SCRIPT" "$LOG" | grep "$TODAY" | wc -l)
if [ "$EXECUTED" -eq 0 ]; then
echo "ALERTA: $SCRIPT no se ha ejecutado hoy"
# Enviar alerta...
fi
Detección de Fallos
Código de Retorno
#!/bin/bash
# Script con gestión de errores
set -e # Detener en error
# Procesamiento...
if ! commande_importante; then
echo "ERROR: Fallo en comando" >&2
exit 1
fi
# Éxito
exit 0
Verificar Código de Retorno
#!/bin/bash
# Verificar fallo en logs
SCRIPT="mon-script.sh"
LOG="/var/log/script.log"
# Buscar errores
ERRORS=$(grep -i "error\|failed\|échec" "$LOG" | wc -l)
if [ "$ERRORS" -gt 0 ]; then
echo "ALERTA: $ERRORS errores en $SCRIPT"
# Enviar alerta...
fi
Alertas por Email
Configuración
# Instalar mail
sudo apt install mailutils # Ubuntu/Debian
sudo yum install mailx # Red Hat/CentOS
# Configuración
# /etc/ssmtp/ssmtp.conf (Ubuntu)
# o
# /etc/mail.rc (Red Hat)
Script con Email
#!/bin/bash
# Script con notificación por email
ALERT_EMAIL="admin@example.com"
SCRIPT_NAME="mon-script.sh"
# Ejecutar script
if /usr/local/bin/mon-script.sh; then
echo "Éxito: $SCRIPT_NAME ejecutado" | \
mail -s "Éxito: $SCRIPT_NAME" "$ALERT_EMAIL"
else
echo "FALLO: $SCRIPT_NAME ha fallado" | \
mail -s "ALERTA: $SCRIPT_NAME" "$ALERT_EMAIL"
exit 1
fi
Crontab con Email
# Crontab
# Enviar salida por email
MAILTO=admin@example.com
0 2 * * * /usr/local/bin/script.sh
# O redirigir a email
0 2 * * * /usr/local/bin/script.sh 2>&1 | mail -s "Reporte" admin@example.com
Alertas Slack
Webhook Slack
#!/bin/bash
# Notificación Slack
SLACK_WEBHOOK="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
SCRIPT_NAME="mon-script.sh"
# Mensaje
MESSAGE="Script $SCRIPT_NAME: $(if [ $? -eq 0 ]; then echo 'Éxito'; else echo 'FALLO'; fi)"
# Enviar
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" \
"$SLACK_WEBHOOK"
Función Reutilizable
#!/bin/bash
# Función notificación Slack
notify_slack() {
local webhook="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
local message="$1"
local status="$2"
local color="good"
[ "$status" != "success" ] && color="danger"
curl -X POST -H 'Content-type: application/json' \
--data "{\"attachments\":[{\"color\":\"$color\",\"text\":\"$message\"}]}" \
"$webhook"
}
# Uso
if mon-script.sh; then
notify_slack "Script exitoso" "success"
else
notify_slack "Script fallido" "failure"
fi
Health Checks
Script de Health Check
#!/bin/bash
# Health check para cron
SCRIPT="mon-script.sh"
LOCK_FILE="/var/run/$SCRIPT.lock"
MAX_AGE=3600 # 1 hora en segundos
# Verificar lock file
if [ -f "$LOCK_FILE" ]; then
AGE=$(($(date +%s) - $(stat -c %Y "$LOCK_FILE")))
if [ "$AGE" -gt "$MAX_AGE" ]; then
echo "ALERTA: Script bloqueado desde hace $AGE segundos"
# Enviar alerta...
rm -f "$LOCK_FILE"
fi
fi
Heartbeat
#!/bin/bash
# Heartbeat para monitoreo
HEARTBEAT_FILE="/var/run/mon-script.heartbeat"
# Actualizar timestamp
touch "$HEARTBEAT_FILE"
# Verificar en monitoreo
# Si heartbeat > 2 horas, alerta
Dashboard de Monitoreo
Script de Reporte
#!/bin/bash
# Reporte cron diario
REPORT="/var/log/cron-report-$(date +%Y%m%d).txt"
{
echo "=== REPORTE CRON $(date) ==="
echo
echo "=== Ejecuciones exitosas ==="
grep "mon-script.sh" /var/log/syslog | grep -v "error" | wc -l
echo
echo "=== Ejecuciones fallidas ==="
grep "mon-script.sh" /var/log/syslog | grep -i "error\|failed" | wc -l
echo
echo "=== Últimas ejecuciones ==="
grep "mon-script.sh" /var/log/syslog | tail -10
echo
echo "=== Estadísticas ==="
echo "Total ejecuciones: $(grep 'mon-script.sh' /var/log/syslog | wc -l)"
} > "$REPORT"
# Enviar por email
mail -s "Reporte Cron $(date +%Y-%m-%d)" admin@example.com < "$REPORT"
Monitoreo Avanzado
Script de Monitoreo Completo
#!/bin/bash
# Monitoreo completo crons
LOG_DIR="/var/log/cron-monitoring"
mkdir -p "$LOG_DIR"
# Lista de crons a monitorear
CRONS=(
"backup.sh"
"cleanup.sh"
"report.sh"
)
for cron in "${CRONS[@]}"; do
# Verificar ejecución
EXECUTED=$(grep "$cron" /var/log/syslog | grep "$(date +%b\ %d)" | wc -l)
# Verificar errores
ERRORS=$(grep "$cron" /var/log/syslog | grep -i "error\|failed" | wc -l)
# Log
echo "$(date): $cron - Ejecuciones: $EXECUTED, Errores: $ERRORS" >> \
"$LOG_DIR/monitoring.log"
# Alerta si hay problema
if [ "$EXECUTED" -eq 0 ] || [ "$ERRORS" -gt 0 ]; then
echo "ALERTA: $cron - Ejecuciones: $EXECUTED, Errores: $ERRORS" | \
mail -s "Alerta Cron" admin@example.com
fi
done
Resumen
En este capítulo, usted ha aprendido:
Monitoreo: Verificar ejecuciones, detectar fallos
Alertas: Email, Slack, notificaciones
Health checks: Lock files, heartbeats
Reportes: Dashboards, estadísticas
Scripts: Automatización de monitoreo
Práctica: Supervisión continua, alertas proactivas
Próximos Pasos
Módulo 12: Administración Avanzada (con automatización de crons)
Fin del Curso: Recapitulación y Proyectos
Capítulo creado el: Diciembre 2024