Configuración de Alertas por Email con mailx
Introducción
El monitoreo proactivo requiere sistemas de notificación efectivos que alerten a los administradores cuando ocurren eventos críticos. Las alertas por email siguen siendo uno de los métodos de notificación más confiables y accesibles universalmente, permitiendo a los administradores de sistemas recibir notificaciones inmediatas sobre problemas del servidor, incidentes de seguridad y anomalías de rendimiento sin importar su ubicación.
La utilidad mailx (también conocida como mail, bsd-mailx o s-nail dependiendo de tu distribución) es un cliente de email ligero de línea de comandos que permite a scripts y aplicaciones enviar emails directamente desde servidores Linux. Cuando se integra con scripts de monitoreo, trabajos cron y servicios del sistema, mailx transforma el registro pasivo en un sistema de alertas activo que te notifica en el momento en que algo requiere atención.
Esta guía completa cubre todo, desde la instalación y configuración básica de mailx hasta estrategias avanzadas de alertas, incluyendo plantillas de email, manejo de adjuntos, emails HTML, integración con servidores SMTP externos y mejores prácticas para prevenir la fatiga de alertas. Ya sea que estés configurando notificaciones simples de trabajos cron o construyendo un sofisticado sistema de alertas de monitoreo, dominar mailx es esencial para una administración de sistemas efectiva.
Requisitos Previos
Antes de configurar alertas por email con mailx, asegúrate de tener:
- Un servidor Linux (Ubuntu 20.04/22.04, Debian 10/11, CentOS 7/8, Rocky Linux 8/9 o similar)
- Acceso root o sudo para instalar paquetes y configurar servicios
- Comprensión básica de protocolos de email (SMTP, MTA)
- Acceso a un servidor SMTP (local o externo como Gmail, SendGrid, etc.)
- Direcciones de email válidas para enviar y recibir alertas
Conocimiento Recomendado:
- Scripting básico en Bash para crear scripts de monitoreo
- Comprensión de agentes de transferencia de correo (MTAs)
- Familiaridad con cron para programación
- Conceptos básicos de redes
Instalación de mailx
El nombre del paquete mailx varía entre distribuciones. Vamos a instalar la versión apropiada para tu sistema.
En Ubuntu/Debian
# Update package repository
sudo apt update
# Install mailutils (includes mailx)
sudo apt install mailutils -y
# Verify installation
mail -V
which mail
Alternativa para bsd-mailx:
# Install bsd-mailx if preferred
sudo apt install bsd-mailx -y
En CentOS/Rocky Linux/AlmaLinux
# Install mailx
sudo yum install mailx -y
# On CentOS 8/Rocky Linux 8+, use s-nail
sudo dnf install s-nail -y
# Verify installation
mail -V
Verificar Instalación
# Check mail command location
which mail
# View mail version
mail -V
# Test basic functionality
echo "Test email" | mail -s "Test Subject" [email protected]
Configuración del Agente de Transferencia de Correo Local (MTA)
Para que mailx pueda enviar emails, necesitas un Agente de Transferencia de Correo. Las opciones más comunes son Postfix y sendmail.
Instalación y Configuración de Postfix
Instalación:
# Ubuntu/Debian
sudo apt install postfix -y
# CentOS/Rocky Linux
sudo yum install postfix -y
Configuración Básica:
# Edit Postfix main configuration
sudo nano /etc/postfix/main.cf
Para entrega local únicamente:
# /etc/postfix/main.cf
myhostname = server.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = loopback-only
mydestination = $myhostname, localhost.$mydomain, localhost
relayhost =
Para relay vía SMTP externo:
# /etc/postfix/main.cf
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
Crear archivo de contraseña SASL:
# Create password file
sudo nano /etc/postfix/sasl_passwd
[smtp.gmail.com]:587 [email protected]:app-password
# Set permissions and create hash database
sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
# Restart Postfix
sudo systemctl restart postfix
sudo systemctl enable postfix
Configuración para Gmail SMTP
Generar Contraseña de Aplicación de Gmail:
- Habilita la autenticación de 2 factores en tu cuenta de Gmail
- Ve a Cuenta de Google > Seguridad > Contraseñas de aplicaciones
- Genera una contraseña de aplicación para "Mail"
Configurar Postfix para Gmail:
# /etc/postfix/main.cf
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_tls_session_cache
Contraseña SASL:
# /etc/postfix/sasl_passwd
[smtp.gmail.com]:587 [email protected]:your-app-password
# Process and restart
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd
sudo systemctl restart postfix
Configuración para SendGrid SMTP
# /etc/postfix/main.cf
relayhost = [smtp.sendgrid.net]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
header_size_limit = 4096000
Contraseña SASL para SendGrid:
# /etc/postfix/sasl_passwd
[smtp.sendgrid.net]:587 apikey:YOUR_SENDGRID_API_KEY
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd
sudo systemctl restart postfix
Uso Básico de mailx
Envío de Emails Simples
Comando básico de email:
# Simple email with subject
echo "This is the email body" | mail -s "Subject Line" [email protected]
# Email with multiple recipients
echo "Email body" | mail -s "Subject" [email protected] [email protected]
# Email from file
mail -s "Subject" [email protected] < email-body.txt
# Interactive email composition
mail -s "Subject" [email protected]
# Type message, then Ctrl+D to send
Establecer Dirección From
# Using -r flag (works on most systems)
echo "Email body" | mail -s "Subject" -r "[email protected]" [email protected]
# Using -a flag for additional headers
echo "Email body" | mail -s "Subject" -a "From: [email protected]" [email protected]
# Setting reply-to address
echo "Email body" | mail -s "Subject" \
-a "From: [email protected]" \
-a "Reply-To: [email protected]" \
[email protected]
Envío de Emails con Adjuntos
# Send file as attachment
echo "Please find attached report" | mail -s "Daily Report" \
-A /path/to/report.pdf \
[email protected]
# Multiple attachments
echo "Logs attached" | mail -s "Server Logs" \
-A /var/log/syslog.gz \
-A /var/log/auth.log.gz \
[email protected]
# Attachment with custom filename
echo "Report attached" | mail -s "Report" \
-a /path/to/file.txt \
[email protected]
Destinatarios CC y BCC
# CC (Carbon Copy)
echo "Email body" | mail -s "Subject" \
-c "[email protected]" \
[email protected]
# BCC (Blind Carbon Copy)
echo "Email body" | mail -s "Subject" \
-b "[email protected]" \
[email protected]
# Both CC and BCC
echo "Email body" | mail -s "Subject" \
-c "[email protected]" \
-b "[email protected]" \
[email protected]
Formato Avanzado de Email
Cuerpos de Email Multi-línea
# Using heredoc
mail -s "Multi-line Message" [email protected] <<EOF
This is line 1
This is line 2
This is line 3
Best regards,
System Administrator
EOF
Desde script:
#!/bin/bash
RECIPIENT="[email protected]"
SUBJECT="System Report"
mail -s "$SUBJECT" "$RECIPIENT" <<EOF
System Monitoring Report
Date: $(date)
Hostname: $(hostname)
Status: All systems operational
Details:
- CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}')
- Memory: $(free -h | grep Mem: | awk '{print $3 "/" $2}')
- Disk: $(df -h / | tail -1 | awk '{print $5}')
Automated monitoring system
EOF
Emails HTML
#!/bin/bash
# send-html-email.sh - Send HTML formatted email
RECIPIENT="[email protected]"
SUBJECT="HTML Report"
# Create HTML content
HTML_CONTENT=$(cat <<'EOF'
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { background-color: #4CAF50; color: white; padding: 10px; }
.content { padding: 20px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #4CAF50; color: white; }
.warning { color: #ff9800; }
.error { color: #f44336; }
</style>
</head>
<body>
<div class="header">
<h2>System Monitoring Report</h2>
</div>
<div class="content">
<p><strong>Server:</strong> server.example.com</p>
<p><strong>Date:</strong> $(date)</p>
<h3>System Status</h3>
<table>
<tr>
<th>Metric</th>
<th>Value</th>
<th>Status</th>
</tr>
<tr>
<td>CPU Usage</td>
<td>45%</td>
<td>OK</td>
</tr>
<tr>
<td>Memory Usage</td>
<td class="warning">82%</td>
<td>Warning</td>
</tr>
<tr>
<td>Disk Usage</td>
<td>65%</td>
<td>OK</td>
</tr>
</table>
</div>
</body>
</html>
EOF
)
# Send HTML email
echo "$HTML_CONTENT" | mail -s "$SUBJECT" \
-a "Content-Type: text/html" \
"$RECIPIENT"
Tablas Formateadas en Texto Plano
#!/bin/bash
# Send formatted table email
{
echo "System Resource Report"
echo "======================"
echo ""
printf "%-20s %-10s %-10s\n" "Resource" "Usage" "Status"
printf "%-20s %-10s %-10s\n" "--------" "-----" "------"
printf "%-20s %-10s %-10s\n" "CPU" "45%" "OK"
printf "%-20s %-10s %-10s\n" "Memory" "82%" "WARNING"
printf "%-20s %-10s %-10s\n" "Disk /" "65%" "OK"
echo ""
echo "Generated: $(date)"
} | mail -s "Resource Report" [email protected]
Integración con Scripts de Monitoreo
Alerta de Monitoreo de CPU
#!/bin/bash
# cpu-alert.sh - Alert on high CPU usage
CPU_THRESHOLD=80
RECIPIENT="[email protected]"
HOSTNAME=$(hostname)
# Get CPU usage
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
CPU_USAGE_INT=${CPU_USAGE%.*}
if [ "$CPU_USAGE_INT" -gt "$CPU_THRESHOLD" ]; then
{
echo "High CPU usage detected on $HOSTNAME"
echo "Current usage: ${CPU_USAGE}%"
echo "Threshold: ${CPU_THRESHOLD}%"
echo "Time: $(date)"
echo ""
echo "Top CPU consumers:"
ps aux --sort=-%cpu | head -n 11
echo ""
echo "Load average:"
uptime
} | mail -s "ALERT: High CPU on $HOSTNAME" "$RECIPIENT"
echo "[$(date)] CPU alert sent" >> /var/log/monitoring/alerts.log
fi
Alerta de Espacio en Disco
#!/bin/bash
# disk-alert.sh - Alert on low disk space
DISK_THRESHOLD=85
RECIPIENT="[email protected]"
HOSTNAME=$(hostname)
# Check all mounted filesystems
df -h | tail -n +2 | while read filesystem size used avail percent mountpoint; do
usage=${percent%\%}
if [ "$usage" -gt "$DISK_THRESHOLD" ]; then
{
echo "Low disk space alert on $HOSTNAME"
echo "Mount point: $mountpoint"
echo "Usage: $percent"
echo "Available: $avail"
echo "Threshold: ${DISK_THRESHOLD}%"
echo "Time: $(date)"
echo ""
echo "Largest directories:"
du -h "$mountpoint" 2>/dev/null | sort -rh | head -n 10
echo ""
echo "Full disk usage:"
df -h
} | mail -s "ALERT: Low Disk Space on $HOSTNAME ($mountpoint)" "$RECIPIENT"
echo "[$(date)] Disk alert sent for $mountpoint" >> /var/log/monitoring/alerts.log
fi
done
Alerta de Monitoreo de Servicios
#!/bin/bash
# service-alert.sh - Alert when service is down
SERVICE="nginx"
RECIPIENT="[email protected]"
HOSTNAME=$(hostname)
if ! systemctl is-active --quiet "$SERVICE"; then
{
echo "Service $SERVICE is DOWN on $HOSTNAME"
echo "Time: $(date)"
echo ""
echo "Service Status:"
systemctl status "$SERVICE" --no-pager
echo ""
echo "Recent Logs:"
journalctl -u "$SERVICE" -n 50 --no-pager
echo ""
echo "Attempting automatic restart..."
} | mail -s "CRITICAL: $SERVICE down on $HOSTNAME" "$RECIPIENT"
# Attempt to restart service
if systemctl start "$SERVICE"; then
{
echo "Service $SERVICE has been automatically restarted on $HOSTNAME"
echo "Time: $(date)"
echo ""
echo "Current Status:"
systemctl status "$SERVICE" --no-pager
} | mail -s "INFO: $SERVICE restarted on $HOSTNAME" "$RECIPIENT"
else
{
echo "FAILED to restart $SERVICE on $HOSTNAME"
echo "Manual intervention required!"
echo "Time: $(date)"
} | mail -s "CRITICAL: Failed to restart $SERVICE on $HOSTNAME" "$RECIPIENT"
fi
fi
Alerta de Seguridad - Intentos de Inicio de Sesión Fallidos
#!/bin/bash
# failed-login-alert.sh - Alert on multiple failed login attempts
THRESHOLD=5
RECIPIENT="[email protected]"
HOSTNAME=$(hostname)
LOG_FILE="/var/log/auth.log" # Use /var/log/secure on CentOS/Rocky
# Count recent failed attempts (last hour)
FAILED_COUNT=$(grep "Failed password" "$LOG_FILE" | \
grep "$(date -d '1 hour ago' '+%b %d %H')" | wc -l)
if [ "$FAILED_COUNT" -gt "$THRESHOLD" ]; then
{
echo "Multiple failed login attempts detected on $HOSTNAME"
echo "Count: $FAILED_COUNT in the last hour"
echo "Threshold: $THRESHOLD"
echo "Time: $(date)"
echo ""
echo "Failed attempts by IP:"
grep "Failed password" "$LOG_FILE" | \
grep "$(date -d '1 hour ago' '+%b %d %H')" | \
awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
echo ""
echo "Failed attempts by username:"
grep "Failed password" "$LOG_FILE" | \
grep "$(date -d '1 hour ago' '+%b %d %H')" | \
awk '{print $(NF-5)}' | sort | uniq -c | sort -rn
echo ""
echo "Recent failed attempts:"
grep "Failed password" "$LOG_FILE" | tail -20
} | mail -s "SECURITY: Failed login attempts on $HOSTNAME" "$RECIPIENT"
fi
Sistema de Alertas de Monitoreo Completo
Script de Monitoreo Multi-Verificación
#!/bin/bash
# comprehensive-alert.sh - Complete monitoring with alerts
# Configuration
RECIPIENT="[email protected]"
HOSTNAME=$(hostname)
LOG_FILE="/var/log/monitoring/alerts.log"
# Thresholds
CPU_THRESHOLD=80
MEM_THRESHOLD=85
DISK_THRESHOLD=90
LOAD_THRESHOLD=2.0
# Alert tracking
ALERTS=()
# Logging function
log_alert() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}
# Check CPU
check_cpu() {
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
local cpu_int=${cpu_usage%.*}
if [ "$cpu_int" -gt "$CPU_THRESHOLD" ]; then
ALERTS+=("High CPU usage: ${cpu_usage}% (threshold: ${CPU_THRESHOLD}%)")
log_alert "CPU alert triggered: ${cpu_usage}%"
fi
}
# Check Memory
check_memory() {
local total=$(free -m | grep Mem: | awk '{print $2}')
local used=$(free -m | grep Mem: | awk '{print $3}')
local percent=$(echo "scale=2; ($used / $total) * 100" | bc)
local percent_int=${percent%.*}
if [ "$percent_int" -gt "$MEM_THRESHOLD" ]; then
ALERTS+=("High memory usage: ${percent}% (threshold: ${MEM_THRESHOLD}%)")
log_alert "Memory alert triggered: ${percent}%"
fi
}
# Check Disk
check_disk() {
while IFS= read -r line; do
local mountpoint=$(echo "$line" | awk '{print $6}')
local percent=$(echo "$line" | awk '{print $5}' | tr -d '%')
if [ "$percent" -gt "$DISK_THRESHOLD" ]; then
ALERTS+=("High disk usage on $mountpoint: ${percent}% (threshold: ${DISK_THRESHOLD}%)")
log_alert "Disk alert triggered for $mountpoint: ${percent}%"
fi
done < <(df -h | tail -n +2 | grep -v "tmpfs")
}
# Check Load Average
check_load() {
local load_1min=$(cat /proc/loadavg | awk '{print $1}')
local cpu_cores=$(nproc)
local load_per_core=$(echo "scale=2; $load_1min / $cpu_cores" | bc)
if (( $(echo "$load_per_core > $LOAD_THRESHOLD" | bc -l) )); then
ALERTS+=("High load average: $load_per_core per core (threshold: $LOAD_THRESHOLD)")
log_alert "Load average alert triggered: $load_per_core"
fi
}
# Check Services
check_services() {
local services=("nginx" "mysql" "redis")
for service in "${services[@]}"; do
if ! systemctl is-active --quiet "$service" 2>/dev/null; then
if systemctl list-unit-files | grep -q "^${service}.service"; then
ALERTS+=("Service $service is not running")
log_alert "Service alert triggered: $service down"
fi
fi
done
}
# Generate and send alert email
send_alerts() {
if [ ${#ALERTS[@]} -eq 0 ]; then
return 0
fi
{
echo "System Alert Report for $HOSTNAME"
echo "=================================="
echo "Time: $(date)"
echo "Alert Count: ${#ALERTS[@]}"
echo ""
echo "ALERTS:"
for alert in "${ALERTS[@]}"; do
echo " - $alert"
done
echo ""
echo "System Status:"
echo "--------------"
echo "CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}')"
echo "Memory: $(free -h | grep Mem: | awk '{print $3 "/" $2}')"
echo "Load Average: $(cat /proc/loadavg | awk '{print $1, $2, $3}')"
echo ""
echo "Disk Usage:"
df -h | grep -v "tmpfs"
echo ""
echo "Top Processes:"
ps aux --sort=-%cpu | head -n 6
echo ""
echo "=================================="
echo "Automated monitoring system"
} | mail -s "ALERT: ${#ALERTS[@]} issue(s) on $HOSTNAME" "$RECIPIENT"
log_alert "Alert email sent to $RECIPIENT"
}
# Main execution
main() {
log_alert "Starting monitoring checks"
check_cpu
check_memory
check_disk
check_load
check_services
send_alerts
if [ ${#ALERTS[@]} -gt 0 ]; then
log_alert "Monitoring completed with ${#ALERTS[@]} alerts"
exit 1
else
log_alert "Monitoring completed - all checks passed"
exit 0
fi
}
main
Mejores Prácticas para Alertas por Email
Prevención de Fatiga de Alertas
Implementar Limitación de Alertas:
#!/bin/bash
# throttled-alert.sh - Prevent duplicate alerts within timeframe
ALERT_TYPE="$1"
COOLDOWN_MINUTES=60
STATE_DIR="/var/lib/monitoring/alerts"
mkdir -p "$STATE_DIR"
# Check if alert was recently sent
if [ -f "$STATE_DIR/$ALERT_TYPE" ]; then
LAST_ALERT=$(cat "$STATE_DIR/$ALERT_TYPE")
CURRENT_TIME=$(date +%s)
TIME_DIFF=$((CURRENT_TIME - LAST_ALERT))
COOLDOWN_SECONDS=$((COOLDOWN_MINUTES * 60))
if [ "$TIME_DIFF" -lt "$COOLDOWN_SECONDS" ]; then
echo "Alert throttled - sent $(( (COOLDOWN_SECONDS - TIME_DIFF) / 60 )) minutes ago"
exit 0
fi
fi
# Send alert and update timestamp
send_alert_function # Your alert function here
echo "$(date +%s)" > "$STATE_DIR/$ALERT_TYPE"
Niveles de Severidad de Alertas
#!/bin/bash
# severity-alerts.sh - Different alerts for different severity levels
send_alert() {
local severity=$1
local subject=$2
local message=$3
case "$severity" in
CRITICAL)
# Send to multiple recipients with urgent flag
echo "$message" | mail -s "CRITICAL: $subject" \
-a "Importance: high" \
-a "Priority: urgent" \
[email protected],[email protected]
# Also send SMS via email gateway
echo "$message" | mail -s "$subject" [email protected]
;;
WARNING)
# Send to admin only
echo "$message" | mail -s "WARNING: $subject" [email protected]
;;
INFO)
# Send daily digest instead of immediate
echo "$message" >> /var/log/monitoring/daily-digest.log
;;
esac
}
# Usage
send_alert "CRITICAL" "Service Down" "Nginx is not responding"
send_alert "WARNING" "High CPU" "CPU usage at 85%"
send_alert "INFO" "Backup Complete" "Daily backup finished successfully"
Reportes de Resumen Diario
#!/bin/bash
# daily-summary.sh - Send daily summary instead of individual emails
SUMMARY_FILE="/var/log/monitoring/daily-summary-$(date +%Y%m%d).log"
RECIPIENT="[email protected]"
# Throughout the day, append to summary file
echo "[$(date)] Event: $EVENT_DESCRIPTION" >> "$SUMMARY_FILE"
# At end of day (via cron), send summary
send_daily_summary() {
if [ ! -f "$SUMMARY_FILE" ]; then
return
fi
{
echo "Daily Summary Report"
echo "===================="
echo "Date: $(date +%Y-%m-%d)"
echo "Hostname: $(hostname)"
echo ""
echo "Events:"
cat "$SUMMARY_FILE"
echo ""
echo "System Status:"
echo "CPU: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}')"
echo "Memory: $(free -h | grep Mem: | awk '{print $3 "/" $2}')"
echo "Disk: $(df -h / | tail -1 | awk '{print $5}')"
} | mail -s "Daily Summary: $(hostname)" "$RECIPIENT"
# Archive summary
mv "$SUMMARY_FILE" "/var/log/monitoring/archive/"
}
# Run this via cron at 11:59 PM
# 59 23 * * * /path/to/daily-summary.sh
Solución de Problemas de Entrega de Email
Probar Entrega de Email
#!/bin/bash
# test-email.sh - Comprehensive email delivery test
echo "Testing email delivery..."
# Test 1: Basic mail command
echo "Test 1: Basic email" | mail -s "Test Email" [email protected]
echo "Sent test email"
# Test 2: Check mail queue
echo ""
echo "Mail queue:"
mailq
# Test 3: Check Postfix status
echo ""
echo "Postfix status:"
systemctl status postfix --no-pager
# Test 4: Check mail logs
echo ""
echo "Recent mail log entries:"
sudo tail -20 /var/log/mail.log # or /var/log/maillog on CentOS
# Test 5: Verify SMTP connection
echo ""
echo "Testing SMTP connection:"
telnet smtp.gmail.com 587
Problemas Comunes y Soluciones
Problema 1: El correo no se está entregando
# Check mail queue
mailq
# View detailed queue
sudo postqueue -p
# Check mail logs
sudo tail -f /var/log/mail.log
# Force queue processing
sudo postfix flush
Problema 2: Falla de autenticación
# Check SASL configuration
sudo postconf -n | grep sasl
# Verify password file
sudo cat /etc/postfix/sasl_passwd
# Check authentication in logs
sudo grep "authentication failed" /var/log/mail.log
# Test SASL authentication
sudo testsaslauthd -u username -p password
Problema 3: Los emails van a spam
# Check SPF record
dig example.com TXT
# Verify DKIM
sudo opendkim-testkey -d example.com -s default
# Check reverse DNS
dig -x YOUR_IP_ADDRESS
# Test email deliverability
# Send test email and check headers
mail -s "Deliverability Test" -v [email protected] < /dev/null
Conclusión
Las alertas por email con mailx proporcionan un sistema de notificación confiable, ligero y flexible para el monitoreo de servidores Linux. Al integrar mailx con scripts de monitoreo, creas una infraestructura de alertas activa que asegura que los eventos críticos nunca pasen desapercibidos.
Puntos clave:
- Simple pero poderoso - mailx ofrece funcionalidad extensa con configuración mínima
- Flexibilidad de integración - Funciona sin problemas con shell scripts, trabajos cron y herramientas de monitoreo
- Opciones SMTP - Configura con MTA local o servicios SMTP externos como Gmail o SendGrid
- Gestión de alertas - Implementa limitación, niveles de severidad y resúmenes diarios para prevenir fatiga de alertas
- Personalización - Crea emails HTML, adjunta archivos y formatea mensajes para máxima claridad
Mejores prácticas para alertas en producción:
- Implementa limitación de alertas para prevenir spam de notificaciones
- Usa niveles de severidad para priorizar diferentes tipos de alertas
- Crea mensajes de alerta claros y accionables con contexto
- Prueba la entrega de email regularmente
- Monitorea el sistema de monitoreo mismo
- Documenta los procedimientos de alerta y protocolos de respuesta
- Usa resúmenes diarios para información no crítica
- Asegura configuración adecuada de SPF, DKIM y DNS inverso
Aunque las alertas por email siguen siendo una piedra angular de la infraestructura de monitoreo, considera complementarlas con otros canales de notificación como SMS, Slack, PagerDuty o integraciones webhook para alertas críticas que requieren atención inmediata. Un enfoque multi-canal asegura que las alertas lleguen a los administradores sin importar las circunstancias, maximizando el tiempo de actividad del sistema y la eficiencia operacional.


