Files
Portainer/crowdsec/metrics-export.sh
T
Eduardo David Paredes Vara 49a7e16da1 feat(crowdsec): añadir stack de detección de intrusiones con Grafana
- docker-compose.yml: CrowdSec + bouncer de Traefik + Postgres + Grafana
- setup.sh: configuración inicial de colecciones, bouncers y whitelist
- metrics-export.sh: exportación de métricas al endpoint de Prometheus
- traefik-crowdsec-bouncer.yml: config dinámica de Traefik para el bouncer
- stack.env: plantilla con API keys y configuración

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 05:48:58 +00:00

56 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
# ============================================================
# crowdsec-metrics-export.sh
# Exporta métricas de CrowdSec a PostgreSQL para Grafana.
# Ejecutar cada 5 minutos via cron.
# ============================================================
set -euo pipefail
PG_DSN="postgresql://crowdsec:crowdsec_metrics_2026@crowdsec-postgres:5432/crowdsec"
# -----------------------------------------------------------
# 1. Decisiones activas (IPs bloqueadas)
# -----------------------------------------------------------
docker exec crowdsec cscli decisions list -o json 2>/dev/null | \
python3 -c "
import sys, json
data = json.load(sys.stdin)
for entry in data:
for d in entry.get('decisions', []):
ip = d.get('value','').replace(chr(39),chr(39)+chr(39))
scenario = d.get('scenario','').replace(chr(39),chr(39)+chr(39))
dtype = d.get('type','').replace(chr(39),chr(39)+chr(39))
origin = d.get('origin','').replace(chr(39),chr(39)+chr(39))
scope = d.get('scope','').replace(chr(39),chr(39)+chr(39))
dur = d.get('duration','').replace(chr(39),chr(39)+chr(39))
print(f'{ip}|{scenario}|{dtype}|{origin}|{scope}|{dur}')
" 2>/dev/null | sort -u > /tmp/cs_decisions.txt
# Limpiar tabla y re-insertar
docker exec crowdsec-postgres psql "$PG_DSN" -c "DELETE FROM decisions" 2>/dev/null
DECISION_COUNT=0
while IFS='|' read -r ip reason action origin scope dur; do
[ -z "$ip" ] && continue
docker exec crowdsec-postgres psql "$PG_DSN" -c "
INSERT INTO decisions (ip, reason, action, origin, scope, duration)
VALUES ('$ip', '$reason', '$action', '$origin', '$scope', '$dur')
" 2>/dev/null || true
DECISION_COUNT=$((DECISION_COUNT + 1))
done < /tmp/cs_decisions.txt
# -----------------------------------------------------------
# 2. Métricas agregadas
# -----------------------------------------------------------
ALERTS=$(docker exec crowdsec cscli alerts list -o json 2>/dev/null | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo 0)
docker exec crowdsec-postgres psql "$PG_DSN" -c "
INSERT INTO metrics (metric_name, metric_value, labels) VALUES
('active_decisions', $DECISION_COUNT, '{}'::jsonb),
('active_alerts', $ALERTS, '{}'::jsonb)
" 2>/dev/null || true
echo "$(date '+%Y-%m-%d %H:%M:%S') crowdsec-metrics: $DECISION_COUNT decisions, $ALERTS alerts"
rm -f /tmp/cs_decisions.txt