🛠 Automatización de Backups con Montaje CIFS y Rsync

🛠 Automatización de Backups con Montaje CIFS y Rsync

Introducción

Este artículo describe cómo implementar un script bash para realizar copias de seguridad nocturnas de varios recursos distribuidos en un entorno de red, combinando montajes CIFS (compartidos en red) y sincronización remota con rsync a través de SSH. El enfoque promueve buenas prácticas de seguridad, legibilidad y mantenimiento.

Objetivos

  • Montar unidades compartidas en red de forma automática y segura.
  • Sincronizar archivos y configuraciones desde un servidor remoto usando rsync.
  • Automatizar todo el proceso para su ejecución diaria (por cron o systemd).
  • Centralizar logs para auditoría y monitoreo.

Estructura del Script

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/bin/bash
set -euo pipefail
# === Configuración General ===
LOG_FILE="/var/log/backup_noche.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$DATE] === Iniciando backup nocturno ===" >> "$LOG_FILE"
# === Credenciales CIFS ===
CIFS_CREDENTIALS="/home/usuario/.smbcredentials"
# Contenido del archivo .smbcredentials:
# username=usuario
# password=tu_contraseña
# === Opciones comunes ===
MOUNT_OPTS="credentials=$CIFS_CREDENTIALS,uid=1000,gid=1000"
RSYNC_OPTS="-avP --delete -e ssh"
# === Rutas de montaje CIFS ===
declare -A CIFS_MOUNTS=(
["//servidor/red/Media"]="/mnt/Media"
["//servidor/red/Backups"]="/mnt/Backups"
["//servidor/red/VMs"]="/mnt/VMs"
)
# === Montar unidades de red ===
for SRC in "${!CIFS_MOUNTS[@]}"; do
DEST="${CIFS_MOUNTS[$SRC]}"
echo "[$DATE] Montando $SRC en $DEST" >> "$LOG_FILE"
if mountpoint -q "$DEST"; then
echo "[$DATE] $DEST ya está montado, omitiendo." >> "$LOG_FILE"
else
sudo mount -t cifs -o "$MOUNT_OPTS" "$SRC" "$DEST" >> "$LOG_FILE" 2>&1
fi
done
# === Rutas de sincronización Rsync ===
RSYNC_HOST="usuario@192.168.1.100"
declare -A RSYNC_JOBS=(
["$RSYNC_HOST:/ruta/remota/bases_de_datos/"]="/mnt/Backups/BasesDeDatos/"
["$RSYNC_HOST:/ruta/remota/configuracion/"]="/mnt/Backups/Configuracion/"
["$RSYNC_HOST:/ruta/remota/datos_usuario/"]="/mnt/Backups/Datos/"
["$RSYNC_HOST:/ruta/remota/software/"]="/mnt/Backups/Software/"
["$RSYNC_HOST:/ruta/remota/sistema/"]="/mnt/Backups/Sistema/"
)
# === Ejecutar sincronizaciones ===
for SRC in "${!RSYNC_JOBS[@]}"; do
DEST="${RSYNC_JOBS[$SRC]}"
echo "[$DATE] Sincronizando $SRC a $DEST" >> "$LOG_FILE"
rsync $RSYNC_OPTS "$SRC" "$DEST" >> "$LOG_FILE" 2>&1
done
echo "[$DATE] === Backup nocturno completado ===" >> "$LOG_FILE"
#!/bin/bash set -euo pipefail # === Configuración General === LOG_FILE="/var/log/backup_noche.log" DATE=$(date "+%Y-%m-%d %H:%M:%S") echo "[$DATE] === Iniciando backup nocturno ===" >> "$LOG_FILE" # === Credenciales CIFS === CIFS_CREDENTIALS="/home/usuario/.smbcredentials" # Contenido del archivo .smbcredentials: # username=usuario # password=tu_contraseña # === Opciones comunes === MOUNT_OPTS="credentials=$CIFS_CREDENTIALS,uid=1000,gid=1000" RSYNC_OPTS="-avP --delete -e ssh" # === Rutas de montaje CIFS === declare -A CIFS_MOUNTS=( ["//servidor/red/Media"]="/mnt/Media" ["//servidor/red/Backups"]="/mnt/Backups" ["//servidor/red/VMs"]="/mnt/VMs" ) # === Montar unidades de red === for SRC in "${!CIFS_MOUNTS[@]}"; do DEST="${CIFS_MOUNTS[$SRC]}" echo "[$DATE] Montando $SRC en $DEST" >> "$LOG_FILE" if mountpoint -q "$DEST"; then echo "[$DATE] $DEST ya está montado, omitiendo." >> "$LOG_FILE" else sudo mount -t cifs -o "$MOUNT_OPTS" "$SRC" "$DEST" >> "$LOG_FILE" 2>&1 fi done # === Rutas de sincronización Rsync === RSYNC_HOST="usuario@192.168.1.100" declare -A RSYNC_JOBS=( ["$RSYNC_HOST:/ruta/remota/bases_de_datos/"]="/mnt/Backups/BasesDeDatos/" ["$RSYNC_HOST:/ruta/remota/configuracion/"]="/mnt/Backups/Configuracion/" ["$RSYNC_HOST:/ruta/remota/datos_usuario/"]="/mnt/Backups/Datos/" ["$RSYNC_HOST:/ruta/remota/software/"]="/mnt/Backups/Software/" ["$RSYNC_HOST:/ruta/remota/sistema/"]="/mnt/Backups/Sistema/" ) # === Ejecutar sincronizaciones === for SRC in "${!RSYNC_JOBS[@]}"; do DEST="${RSYNC_JOBS[$SRC]}" echo "[$DATE] Sincronizando $SRC a $DEST" >> "$LOG_FILE" rsync $RSYNC_OPTS "$SRC" "$DEST" >> "$LOG_FILE" 2>&1 done echo "[$DATE] === Backup nocturno completado ===" >> "$LOG_FILE"
#!/bin/bash
set -euo pipefail

# === Configuración General ===
LOG_FILE="/var/log/backup_noche.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$DATE] === Iniciando backup nocturno ===" >> "$LOG_FILE"

# === Credenciales CIFS ===
CIFS_CREDENTIALS="/home/usuario/.smbcredentials"
# Contenido del archivo .smbcredentials:
# username=usuario
# password=tu_contraseña

# === Opciones comunes ===
MOUNT_OPTS="credentials=$CIFS_CREDENTIALS,uid=1000,gid=1000"
RSYNC_OPTS="-avP --delete -e ssh"

# === Rutas de montaje CIFS ===
declare -A CIFS_MOUNTS=(
  ["//servidor/red/Media"]="/mnt/Media"
  ["//servidor/red/Backups"]="/mnt/Backups"
  ["//servidor/red/VMs"]="/mnt/VMs"
)

# === Montar unidades de red ===
for SRC in "${!CIFS_MOUNTS[@]}"; do
  DEST="${CIFS_MOUNTS[$SRC]}"
  echo "[$DATE] Montando $SRC en $DEST" >> "$LOG_FILE"
  if mountpoint -q "$DEST"; then
    echo "[$DATE] $DEST ya está montado, omitiendo." >> "$LOG_FILE"
  else
    sudo mount -t cifs -o "$MOUNT_OPTS" "$SRC" "$DEST" >> "$LOG_FILE" 2>&1
  fi
done

# === Rutas de sincronización Rsync ===
RSYNC_HOST="usuario@192.168.1.100"
declare -A RSYNC_JOBS=(
  ["$RSYNC_HOST:/ruta/remota/bases_de_datos/"]="/mnt/Backups/BasesDeDatos/"
  ["$RSYNC_HOST:/ruta/remota/configuracion/"]="/mnt/Backups/Configuracion/"
  ["$RSYNC_HOST:/ruta/remota/datos_usuario/"]="/mnt/Backups/Datos/"
  ["$RSYNC_HOST:/ruta/remota/software/"]="/mnt/Backups/Software/"
  ["$RSYNC_HOST:/ruta/remota/sistema/"]="/mnt/Backups/Sistema/"
)

# === Ejecutar sincronizaciones ===
for SRC in "${!RSYNC_JOBS[@]}"; do
  DEST="${RSYNC_JOBS[$SRC]}"
  echo "[$DATE] Sincronizando $SRC a $DEST" >> "$LOG_FILE"
  rsync $RSYNC_OPTS "$SRC" "$DEST" >> "$LOG_FILE" 2>&1
done

echo "[$DATE] === Backup nocturno completado ===" >> "$LOG_FILE"

Configuración Requerida

1. Archivo de credenciales .smbcredentials

Guarda este archivo en /home/usuario/.smbcredentials con permisos restrictivos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
chmod 600 ~/.smbcredentials
chmod 600 ~/.smbcredentials
chmod 600 ~/.smbcredentials

Contenido:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
username=usuario
password=tu_contraseña
username=usuario password=tu_contraseña
username=usuario
password=tu_contraseña

2. Permisos de Montaje

Asegúrate de que el usuario tiene privilegios sudo para montar unidades CIFS. Puedes permitir solo el comando mount en el sudoers si deseas limitar los privilegios.

Automatización del Backup

Opción 1: Programación con Cron

Edita la crontab del usuario:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
crontab -e
crontab -e
crontab -e

Y agrega la siguiente línea para ejecutarlo cada noche a las 2 AM:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
0 2 * * * /ruta/al/script/backup_nocturno.sh
0 2 * * * /ruta/al/script/backup_nocturno.sh
0 2 * * * /ruta/al/script/backup_nocturno.sh

✅ Opción recomendada: Programación con systemd

1. Archivo de servicio backup-nocturno.service

Guárdalo en:
/etc/systemd/system/backup-nocturno.service

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[Unit]
Description=Backup nocturno con CIFS y Rsync
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/ruta/al/script/backup_nocturno.sh
User=usuario
Group=usuario
Nice=10
ProtectSystem=full
ProtectHome=yes
PrivateTmp=true
StandardOutput=journal
StandardError=journal
[Unit] Description=Backup nocturno con CIFS y Rsync After=network-online.target Wants=network-online.target [Service] Type=oneshot ExecStart=/ruta/al/script/backup_nocturno.sh User=usuario Group=usuario Nice=10 ProtectSystem=full ProtectHome=yes PrivateTmp=true StandardOutput=journal StandardError=journal
[Unit]
Description=Backup nocturno con CIFS y Rsync
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/ruta/al/script/backup_nocturno.sh
User=usuario
Group=usuario
Nice=10
ProtectSystem=full
ProtectHome=yes
PrivateTmp=true
StandardOutput=journal
StandardError=journal

Cambia la ruta del script y el nombre de usuario según tu entorno.

2. Archivo del temporizador backup-nocturno.timer

Guárdalo en:
/etc/systemd/system/backup-nocturno.timer

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[Unit]
Description=Timer para backup nocturno diario
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
[Unit] Description=Timer para backup nocturno diario [Timer] OnCalendar=*-*-* 02:00:00 Persistent=true [Install] WantedBy=timers.target
[Unit]
Description=Timer para backup nocturno diario

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

Este temporizador ejecuta el script cada día a las 2:00 AM.

3. Activación

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Recargar systemd
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
# Habilitar el temporizador
sudo systemctl enable --now backup-nocturno.timer
# Recargar systemd sudo systemctl daemon-reexec sudo systemctl daemon-reload # Habilitar el temporizador sudo systemctl enable --now backup-nocturno.timer
# Recargar systemd
sudo systemctl daemon-reexec
sudo systemctl daemon-reload

# Habilitar el temporizador
sudo systemctl enable --now backup-nocturno.timer

4. Verificación

Para ver cuándo se ejecutó y cuándo se ejecutará:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
systemctl list-timers | grep backup-nocturno
systemctl list-timers | grep backup-nocturno
systemctl list-timers | grep backup-nocturno

Ver los logs del servicio:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
journalctl -u backup-nocturno.service
journalctl -u backup-nocturno.service
journalctl -u backup-nocturno.service

Conclusión

Este sistema de backups es modular, seguro y fácilmente auditable. Usar systemd en lugar de cron aporta ventajas de gestión, trazabilidad y control de errores. Con esta base puedes seguir escalando tus tareas de respaldo de forma organizada.

Comentarios

Aún no hay comentarios. ¿Por qué no comienzas el debate?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *