miércoles, 19 de junio de 2019

Script y tarea para hacer backup de ficheros de configuración de equipos

Para hacer los backups del servidor del centro utilizo un script o sistema parecido al que aparece en este post.

Es aconsejable tener una copia de los archivos de configuración de diferentes servicios de cada máquina, ya que los datos pueden ser diferentes de una a otra y además puede ser que no se controlen por puppet. De esta manera, después de clonar podemos restaurar dichos archivos en un momento.

He hecho un script basándome en el que utilizo para el servidor.
Utilizo un servidor openmediavault por el que comparto los backups y monto por nfs el directorio para guardarlos.

Mediante puppet distribuyo los archivos de la tarea:
- El script, en resumen hace un backup incremental por rsync de una lista de archivos que almaceno en un archivo archivos.includes. Lo almaceno en /var/backups y luego copio por nfs a la máquina de almacenamiento.

root@servidor:/etc/puppet/modules/mp-xubuntu-ficheros-centro/files# cat bin/backupHost.sh 
#!/bin/sh

#########################################################
# Script to do incremental rsync backups
# Adapted from script found on the rsync.samba.org
# Brian Hone 3/24/2002
# This script is freely distributed under the GPL
#
# Para que este script funcione correctamente, desde en el 
# servidor que utilicemos para backup se deben generar las
# claves RSA y DSA mediante el comando:
#    ssh-keygen -t rsa -b 1024
#    ssh-keygen -t dsa -b 1024
#
# Los archivos *.pub generados en el directorio /root/.ssh/ de esa
# máquina se deben copiar a dicha máquina y añadir al fichero 
# /root/.ssh/authorized_keys:
#   cat *.pub >> ~/.ssh/authorized_keys
#
#########################################################


##################################
# Configure These Options
##################################


###################################
# HOSTNAME
#  - This is also used for reporting
#  - Debe responder a un ping (Ej ping quercus).
#  - Su valor corresponderá con el directorio 
#    en el que se almacenarán los backups de ese host
#    Ej: Si HOSTNAME es "mi_host" los backups se guardarán en
#    /var/backups/mi_host/
###################################
HOSTNAME=`facter fqdn`

###################################
# directory to backup
# - This is the path to the directory you want to archive
###################################
BACKUPDIR=/

###################################
# excludes file - contains one wildcard pattern per line of files to exclude
#  - This is a rsync exclude file.  See the rsync man page and/or the
#    example_exclude_file
###################################
EXCLUDES=/usr/local/bin/backup/archivos.excluded
INCLUDES=/usr/local/bin/backup/archivos.included

###################################
# root directory to for backup stuff
###################################
ARCHIVEROOT=/var/backups
#ARCHIVEROOT=/export/Backups/backupltsp

#########################################
# From here on out, you probably don't  #
#   want to change anything unless you  #
#   know what you're doing.             #
#########################################

# directory which holds our current datastore
CURRENT=main

# directory which we save incremental changes to
INCREMENTDIR=`date +%Y-%m-%d`
HORA=`+%c`
#DIAS QUE SE GUARDAN LOS BACKUPS
DIASBORRADO=85

# options to pass to rsync
OPTIONS="--force --ignore-errors --delete --delete-excluded  --files-from=$INCLUDES --backup --backup-dir=$ARCHIVEROOT/$HOSTNAME/$INCREMENTDIR -av"

# make sure our backup tree exists
install -d $ARCHIVEROOT/$HOSTNAME/$CURRENT

# our actual rsyncing function
do_rsync()
{
   #creamos la carpeta donde vamos a guardar los backups, si no existiera
   touch /var/backups
   echo "$HORA  Comenzando backup de $HOSTNAME en $ARCHIVEROOT/$HOSTNAME/$CURRENT"
   echo "$HORA  Borrando Bakcups antiguos de $HOSTNAME ">> /usr/local/bin/backup/backup.log
        # Para ver las copias que se van a eliminarAlmacenamos en archivo log: 
        echo "borramos backups antiguos" >> /usr/local/bin/backup/backup.log
        find $ARCHIVEROOT/$HOSTNAME -maxdepth 1 -mtime +$DIASBORRADO -not -iname main -exec echo {} + >> /usr/local/bin/backup/backup.log
        # y las borramos
        find $ARCHIVEROOT/$HOSTNAME -maxdepth 1 -mtime +$DIASBORRADO -not -iname main -exec rm -rf {} +;
   echo "$HORA  Comenzando backup de $HOSTNAME en $ARCHIVEROOT/$HOSTNAME/$CURRENT">> /usr/local/bin/backup/backup.log
   rsync $OPTIONS $BACKUPDIR $ARCHIVEROOT/$HOSTNAME/$CURRENT
   echo "$HORA  Backup de $HOSTNAME finalizado" >> /usr/local/bin/backup/backup.log
   echo "----------------------------------------------------------------"
   echo "----------------------------------------------------------------">> /usr/local/bin/backup/backup.log
}

# some error handling and/or run our backup and accounting
#if [ -f $EXCLUDES ]; then
if [ -f $INCLUDES ]; then
if [ -d $BACKUPDIR ]; then
# now the actual transfer
do_rsync
# montamos y copiamos por nfs los archivos de backup en la máquina donde guardamos todos los backups de las diferentes máquinas 
mount -t nfs maquinaNFS:/export/Backups /mnt
cp -rf /var/backups/$HOSTNAME /mnt/backupltsp/
umount /mnt/
else
echo "cant find $BACKUPDIR">> /usr/local/bin/backup/backup.log
echo "cant find $BACKUPDIR"; exit
fi

else
echo "cant find $INCLUDES" >> /usr/local/bin/backup/backup.log
echo "cant find $INCLUDES"; exit
fi


- El fichero con lista de archivos a hacer copia: archivos.includes

root@servidor:/etc/puppet/modules/mp-xubuntu-ficheros-centro/files# cat bin/backup
backup/        backupHost.sh  
root@servidor:/etc/puppet/modules/mp-xubuntu-ficheros-centro/files# cat bin/backup/
archivos.excluded  archivos.included  backup.log         
root@servidor:/etc/puppet/modules/mp-xubuntu-ficheros-centro/files# cat bin/backup/archivos.included 
/etc/netplan/01-network-manager-all.yaml
/etc/escuela2.0
/etc/hostname
/etc/hosts
/etc/udev/rules.d/70-persistent-net.rules
/var/lib/aulalinex-profesor/aulalinex-profesor.conf
/var/lib/aulalinex-profesor-ltsp/setup.ini
/etc/hostapd/hostapd.accept
/etc/hostapd/hostapd.conf
/etc/hostapd/hostapd.deny
/etc/SIATIC/siaticcontrol.ini 
/usr/share/linex-ubuntu-puppet/escuela2.0
/etc/zabbix/zabbix_agentd.conf
/etc/controlwifi/controlwifi.conf
/etc/controlwifi/profesor_control_wifi.conf
/etc/cups/printers.conf
/var/spool/cron/crontabs/root


- Un fichero con lista de archivos que deseo excluir (no lo utilizo pero podría): archivos.excludes


- Un crontab para que se ejecute una vez en semana.
                # el cron para hacer backup de los ficheros de configuracion module mp-xubuntu-ficheros-centro/files/bin/backupHost.sh
                cron {  "backupSemanal":
                        command => "/usr/local/bin/backupHost.sh",
                        user => root,
                        weekday => "*/1",
                        ensure => present,
                }


- Para restaurar los archivos utilizaríamos el siguiente script:
root@servidor:/usr/local/bin/backup# cat /bin/restauraHost.sh 
#!/bin/bash
#
# nombre              : restauraHost.sh
# descripción         : Restaurar archivos de configuracion de host
# autor               : José Miguel Medina
# fecha creación      : 20062019
# última modificación : 20062019
# uso                 : ./restauraHost.sh
# instalación         : Guardar en  /usr/local/bin/

#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License at <http://www.gnu.org/licenses/> for
# more details.
#

HOSTNAME=`facter fqdn`

###################################
# directorio a resturar
# - This is the path to the directory you want to restaure
###################################
BACKUPDIR=/

###################################
# excludes file - contains one wildcard pattern per line of files to exclude
#  - This is a rsync exclude file.  See the rsync man page and/or the
#    example_exclude_file
###################################
EXCLUDES=/usr/local/bin/backup/archivos.excluded
INCLUDES=/usr/local/bin/backup/archivos.included

###################################
# Directorio donde se montan copia de seguridad
###################################
ARCHIVEROOT=/mnt/backupltsp
#ARCHIVEROOT=/export/Backups/backupltsp

#########################################
# From here on out, you probably don't  #
#   want to change anything unless you  #
#   know what you're doing.             #
#########################################

# directory which holds our current datastore
CURRENT=main


# options to pass to rsync

# our actual rsyncing function
do_rsync()
{
   # montamos y copiamos por nfs los archivos de backup en la máquina donde guardamos todos los backups de las diferentes máquinas
   mount -t nfs equipoBackups:/export/Backups /mnt

   # restauramos la copia de seguridad
   rsync $OPTIONS $ARCHIVEROOT/$HOSTNAME/$CURRENT $BACKUPDIR 2>1

   # y desmontamos la máquina de backups
   umount /mnt/

}

# some error handling and/or run our backup and accounting
#if [ -f $EXCLUDES ]; then
if [ -f $INCLUDES ]; then
if [ -d $BACKUPDIR ]; then
# now the actual transfer
do_rsync
else
echo "cant find $BACKUPDIR"; exit
fi

else
echo "cant find $INCLUDES"; exit
fi


No hay comentarios:

Publicar un comentario