Files
topdir/CASOS_DE_USO.md
2025-10-31 00:29:18 +01:00

9.1 KiB

Casos de Uso Prácticos - topdir.sh

1. Monitoreo de backups

Detectar cambios en directorio de backups para saber qué archivos han sido actualizados:

# Configurar monitoreo diario vía cron
# /etc/cron.d/backup-monitor
0 6 * * * root /usr/local/bin/topdir.sh \
  --snapshot-file /var/lib/topdir/backup.snap \
  --format json \
  --exclude "*.log" \
  /backup/data > /var/log/backup-changes.json 2>&1

Analizar resultados:

# Ver qué se modificó hoy
jq -r '.modified[]' /var/log/backup-changes.json

# Contar archivos nuevos
jq '.new | length' /var/log/backup-changes.json

2. Auditoría de cambios en servidores

Monitorear directorios críticos para detectar modificaciones no autorizadas:

# Crear snapshot de referencia (línea base de seguridad)
topdir.sh --snapshot-file /root/security/etc.snap /etc

# Ejecutar periódicamente para detectar cambios
topdir.sh --snapshot-file /root/security/etc.snap \
  --format json \
  /etc | tee /var/log/etc-changes.json

# Alertar si hay cambios
CHANGES=$(jq -r '.new + .modified + .deleted | length' /var/log/etc-changes.json)
if [ "$CHANGES" -gt 0 ]; then
  echo "ALERTA: $CHANGES archivos cambiaron en /etc" | \
    mail -s "Cambios en /etc" admin@example.com
fi

3. CI/CD - Detectar qué archivos cambiaron

Optimizar pipelines ejecutando solo tests afectados:

#!/bin/bash
# ci-smart-test.sh

# Detectar cambios desde último build exitoso
./topdir.sh --format json \
  --snapshot-file ~/.ci/last-success.snap \
  --exclude "*.md" \
  --exclude "docs/*" \
  . > changes.json

# Si cambiaron archivos Python, ejecutar tests Python
if jq -r '.new + .modified | .[]' changes.json | grep -q '\.py$'; then
  echo "Cambios en Python detectados, ejecutando pytest..."
  pytest
fi

# Si cambiaron archivos JS, ejecutar tests JS
if jq -r '.new + .modified | .[]' changes.json | grep -q '\.(js|ts)$'; then
  echo "Cambios en JS/TS detectados, ejecutando jest..."
  npm test
fi

# Si todos los tests pasan, actualizar snapshot
if [ $? -eq 0 ]; then
  ./topdir.sh . > /dev/null  # Actualiza snapshot
fi

4. Sincronización selectiva

Sincronizar solo archivos que cambiaron (más eficiente que rsync completo):

#!/bin/bash
# sync-changes.sh

SOURCE="/data/project"
DEST="user@server:/remote/project"
SNAPSHOT="/tmp/sync.snap"

# Detectar cambios
./topdir.sh --format csv --snapshot-file "$SNAPSHOT" "$SOURCE" > changes.csv

# Sincronizar solo archivos nuevos y modificados
while IFS=, read -r status path; do
  if [ "$status" = "new" ] || [ "$status" = "modified" ]; then
    # Quitar comillas y ./ del path
    clean_path=$(echo "$path" | sed 's/"//g' | sed 's|^\./||')
    echo "Sincronizando: $clean_path"
    rsync -avz "$SOURCE/$clean_path" "$DEST/$clean_path"
  fi
done < <(tail -n +2 changes.csv)  # Saltar header CSV

echo "Sincronización completada"

5. Detección de intrusiones básica

Monitorear directorios de aplicación web:

#!/bin/bash
# web-monitor.sh

WEB_ROOT="/var/www/html"
SNAPSHOT="/var/lib/topdir/web.snap"

# Primera ejecución: crear baseline
if [ ! -f "$SNAPSHOT" ]; then
  topdir.sh --snapshot-file "$SNAPSHOT" \
    --exclude "uploads/*" \
    --exclude "cache/*" \
    --exclude "*.log" \
    "$WEB_ROOT"
  echo "Baseline creado en $SNAPSHOT"
  exit 0
fi

# Chequear cambios
REPORT=$(topdir.sh --snapshot-file "$SNAPSHOT" \
  --format json \
  --exclude "uploads/*" \
  --exclude "cache/*" \
  --exclude "*.log" \
  "$WEB_ROOT")

# Analizar cambios sospechosos
NEW=$(echo "$REPORT" | jq -r '.new | length')
MOD=$(echo "$REPORT" | jq -r '.modified | length')

if [ "$NEW" -gt 0 ] || [ "$MOD" -gt 0 ]; then
  {
    echo "ALERTA: Cambios detectados en $WEB_ROOT"
    echo ""
    echo "Archivos nuevos ($NEW):"
    echo "$REPORT" | jq -r '.new[]'
    echo ""
    echo "Archivos modificados ($MOD):"
    echo "$REPORT" | jq -r '.modified[]'
  } | mail -s "Cambios en servidor web" security@example.com
  
  # Loggear para análisis
  echo "$REPORT" | jq . >> /var/log/web-changes.log
fi

6. Desarrollo - Pre-commit hook

Revisar qué archivos se van a commitear:

#!/bin/bash
# .git/hooks/pre-commit

# Crear snapshot temporal del directorio staged
git diff --cached --name-only --diff-filter=ACM > /tmp/staged-files.txt

# Ejecutar linter solo en archivos modificados
while read -r file; do
  if [[ $file == *.py ]]; then
    pylint "$file" || exit 1
  elif [[ $file == *.js ]]; then
    eslint "$file" || exit 1
  fi
done < /tmp/staged-files.txt

# Alternativamente, usar topdir.sh para detectar cambios desde último commit
./topdir.sh --format json . | jq -r '.modified[]' | while read -r file; do
  echo "Verificando: $file"
  # Ejecutar checks aquí
done

7. Análisis de actividad de desarrollo

Generar estadísticas de cambios en el proyecto:

#!/bin/bash
# dev-stats.sh

PROJECT="/home/user/myproject"
STATS_DIR="/home/user/.dev-stats"
DATE=$(date +%Y-%m-%d)

mkdir -p "$STATS_DIR"

# Capturar snapshot diario
./topdir.sh --format json \
  --snapshot-file "$STATS_DIR/snapshot-$DATE.json" \
  --exclude "node_modules/*" \
  --exclude ".git/*" \
  "$PROJECT" > "$STATS_DIR/changes-$DATE.json"

# Analizar histórico mensual
echo "Estadísticas del último mes:"
for file in "$STATS_DIR"/changes-*.json; do
  date=$(basename "$file" .json | cut -d- -f2-)
  new=$(jq '.new | length' "$file")
  mod=$(jq '.modified | length' "$file")
  del=$(jq '.deleted | length' "$file")
  echo "$date: +$new ~$mod -$del"
done | sort

# Archivos más modificados (requiere análisis histórico)
jq -r '.modified[]' "$STATS_DIR"/changes-*.json | \
  sort | uniq -c | sort -rn | head -10

8. Monitoreo de logs con rotación

Detectar nuevos archivos de log sin rastrear archivos rotados:

#!/bin/bash
# log-monitor.sh

LOG_DIR="/var/log/myapp"
SNAPSHOT="/var/lib/topdir/logs.snap"

# Monitorear solo logs activos (excluir .gz, .1, .2, etc.)
./topdir.sh --format json \
  --snapshot-file "$SNAPSHOT" \
  --exclude "*.gz" \
  --exclude "*.1" \
  --exclude "*.2" \
  --exclude "*.old" \
  "$LOG_DIR" | \
  jq -r '.new[]' | \
  while read -r logfile; do
    echo "Nuevo log detectado: $logfile"
    # Configurar monitoring
    tail -f "$LOG_DIR/$logfile" | grep -i error &
  done

9. Gestión de configuraciones

Trackear cambios en archivos de configuración:

#!/bin/bash
# config-tracker.sh

CONFIG_DIRS=(
  "/etc/nginx"
  "/etc/systemd"
  "/etc/mysql"
)

for dir in "${CONFIG_DIRS[@]}"; do
  service=$(basename "$dir")
  snapshot="/var/lib/topdir/config-$service.snap"
  
  echo "Verificando $dir..."
  
  changes=$(./topdir.sh --format json \
    --snapshot-file "$snapshot" \
    "$dir")
  
  total_changes=$(echo "$changes" | \
    jq '(.new + .modified + .deleted) | length')
  
  if [ "$total_changes" -gt 0 ]; then
    echo "⚠️  $total_changes cambios en $service"
    echo "$changes" | jq '{new, modified, deleted}'
    
    # Crear backup antes de aceptar cambios
    tar -czf "/backup/config-$service-$(date +%s).tar.gz" "$dir"
    echo "✓ Backup creado"
  else
    echo "✓ Sin cambios en $service"
  fi
  echo ""
done

10. Docker - Detectar cambios en volúmenes

Monitorear qué archivos cambian en volúmenes Docker:

#!/bin/bash
# docker-volume-monitor.sh

VOLUME_PATH="/var/lib/docker/volumes/myapp_data/_data"
SNAPSHOT="/tmp/docker-volume.snap"

# Primera vez
if [ ! -f "$SNAPSHOT" ]; then
  ./topdir.sh --snapshot-file "$SNAPSHOT" "$VOLUME_PATH"
  echo "Snapshot inicial creado"
  exit 0
fi

# Detectar cambios
./topdir.sh --format json \
  --snapshot-file "$SNAPSHOT" \
  "$VOLUME_PATH" | \
  jq '{
    summary: {
      new: (.new | length),
      modified: (.modified | length),
      deleted: (.deleted | length)
    },
    changes: {
      new: .new,
      modified: .modified,
      deleted: .deleted
    }
  }'

# Crear punto de restauración si hay muchos cambios
TOTAL=$(./topdir.sh --format json "$VOLUME_PATH" | \
  jq '(.new + .modified) | length')

if [ "$TOTAL" -gt 100 ]; then
  echo "Muchos cambios detectados, creando snapshot Docker..."
  docker commit myapp_container myapp:snapshot-$(date +%s)
fi

Consejos de rendimiento

Para directorios grandes (>100k archivos)

# Usar MD5 (más rápido)
./topdir.sh --hash md5 /large/directory

# Excluir directorios grandes no relevantes
./topdir.sh \
  --exclude "node_modules/*" \
  --exclude ".git/*" \
  --exclude "cache/*" \
  /large/directory

Para sistemas de archivos de red (NFS, CIFS)

# Guardar snapshot localmente para evitar I/O de red
./topdir.sh \
  --snapshot-file /tmp/network-share.snap \
  /mnt/network-share

Automatización con systemd timer

# /etc/systemd/system/topdir-monitor.timer
[Unit]
Description=Topdir monitoring timer

[Timer]
OnCalendar=hourly
Persistent=true

[Install]
WantedBy=timers.target
# /etc/systemd/system/topdir-monitor.service
[Unit]
Description=Topdir directory monitoring

[Service]
Type=oneshot
ExecStart=/usr/local/bin/topdir.sh \
  --format json \
  --snapshot-file /var/lib/topdir/main.snap \
  /data/important
StandardOutput=append:/var/log/topdir-monitor.log

Activar:

systemctl enable --now topdir-monitor.timer
systemctl list-timers