lunes, 13 de agosto de 2012

Backup Configuration Files

Este es una version "mejorada" del escript que postee hace tiempo para grabar los arhcivos de configuración. Esta versión es más facil de usar, mas robusta, y con menos líneas de código ;) también me deshice de la parte hard coded del script.

El script puede respaldar los archivos de configuración que desees salvar, y también puede restaurar los mismos.

Para funcionar el script necesita 2 parametros y se corre así:

Digamos que queremos hacer un respaldo de algunos archivos de configuracion. Para poder respaldarlos con el script debemos hacer un archivo de texto que contenga los archivos que queremos guardar.

Ejemplo.


/etc/hosts
/etc/httpd/conf/httpd.conf
/home/jorge/miArchivo
/etc/mail/main.cf

Ahora supongamos que nuestro archivo de texto que contiene la lista de los archivos que queremos respaldar se llama "listaArchivos"

Para hacer el respaldo de los archivos mencionados en listaArchivos corremos lo siguiente:

$ sudo ./configBackup -b listaArchivos
 
Este producira de output un archivo de nombre: configBackup-dia-mes-año.tgz

Ejem. Si hoy es 5 de Marzo de 2011 se llamara

configBackup-5-03-2011.tgz

Este archivo contiene todos los archivos que mencionamos en listaArchivos comprimidos dentro de el. No importa si existen archivos con nombres iguales

El script tiene la capacidad de restaurar todos los archivos a su lugar original. Es decir es genial si neceistas hacer un respaldo y luego restaurar y dejar todo como estaba exactamente.

Si queremos hacer el restore, es decir, recuperar nuestro archivos y colocarlos donde estaban cuando hicimos el respaldo corremos.

$ sudo ./configBackup -r configBackup-5-03-2011.tgz
 
El script te avisa si hubo problemas al hacer el backup o el restore de los achivos.

No es necesario correrlo como root, pero esto depende de los permisos de los archivos que quieras respaldar. De cualquier manera el script grabara lo que pueda.

El codigo esta en GitHbu aquí!

#!/bin/bash
currentDate=`date +%F` # Gets current day in full formate
outputName="configBackup-$currentDate"; # Sets the output file name
tmp="/tmp"; # Sets temp folder location
randStr=`</dev/urandom tr -dc A-Za-z0-9 | head -c8`; # Stores a random string of letters and numbers of 8 characters in length
tmpFullDirName=$tmp/"configBackup-$randStr" # Sets the name of temporal folder from where the script will work
backupTargetDir=$tmpFullDirName; # Sets the temporal folder that we'll backup, this is the full previous variable
workingDir=`pwd` # Gets the folder path from where we ran the script
folderList=`ls -l | egrep '^d' | awk '{ print $9 }'`
bkSourceName="bkSource.bks" #Name of the source file, we will rename it to this value
#
# Prints help message to the user
#
function usage
{
echo "Usage: $0 [options] source_list OR backup_file.tgz"
echo
echo "Options:"
echo " -b backup your configuration files "
echo " -r restore your configuration files "
echo "[source_list] File containing the paths of the configuration files to backup"
echo "[backup_file.tgz] Previosly created backup file, must have been created with this tool!"
echo
echo "Examples: "
echo
echo "Backup configuration files from files_list.txt source file"
echo "$0 -b files_list.txt"
echo
echo "Restore configuration files from previous backup file"
echo "$0 -r configBackup-2011-08-29.tgz"
echo
exit
}
#
# Creates a temporary folder inside $tmp, move to it, then iterate through the source list file that contains
# the names of files to backup. For each file create a folder named after the full path of each file, then
# copy each file into its corresponding folder. This is to avoid overwrites when two or more files have the
# same name.
#
function backup
{
#First create a tmp dir to store files
mkdir $tmpFullDirName
tmpDir=$tmpFullDirName
# Now lets copy backup source file to use on restore if necessary, if the copy fails restore function cannot work
cp $workingDir/$1 $tmpDir/$bkSourceName || echo "Backup source file copy failed, restore function will be unavailable"
#Get the contents of the file list
LIST=`cat $workingDir/$1`
for i in $LIST
do
RESULT=`mkdir -p $tmpDir\$i`
cd $tmpDir/$i
cp --preserve=all $i ./ 2>&1 || echo "Copy of $i failed"
done
}
function restore
{
#Folder is creted during extraction for obvious reasons
# Gets the content of the backup source file. If cannot be read or doesnt exists restore cannot work
LIST=`cat $tmpDir/$bkSourceName || echo "Could not open file $bkSourceName, it maybe that the process failed during the creation of the backup. Restore function is disabled!!! Will exit now!;exit;"`
{
for i in $LIST
do
####### Used for debugging
## RESULT=`mkdir -p $tmpDir\$i`
## cd $tmpDir/$i
#######
# Next creates a folder after each file full path under current path, to avoid overwrite for files with same name
# Ugly but works cause ech file as its own folder name after itself
cp --preserve=all --no-preserve=timestamps $tmpDir/$i/* $i || echo "Restore failed on $i"
done
} && {
echo "Restore successful!"
} || {
echo "Restore completed with errors"
}
}
#
# Compress the $backupTargetDir folder retaining as much attributes ass posible, then output success or failure
#
function compress
{
cd $backupTargetDir
{
tar czpf $outputName.tgz --same-owner --exclude=$outputName.tgz *
} && {
echo -e "Backup...OK \nOutput files is $outputName.tgz";
} || {
echo "Backup...Failed!";
}
}
#
# Extracts the $outputName.tgz file, then output success or failure
#
function extract
{
mkdir $tmpFullDirName
tmpDir=$tmpFullDirName
{
tar xzpf $workingDir/$1 -C $tmpFullDirName
} && {
echo -e "Extraction...Ok!";
} || {
echo "Extraction...Failed!";echo "Fatal error will quit";exit;
}
}
#
# Move the compressed output file to the $workingDir folder
#
function moveIt
{
cd $backupTargetDir
mv $outputName.tgz $workingDir
}
#
# Remove the folder we created in $tmp is no longer useful
#
function clean
{
rm -fr $tmpFullDirName
}
#
# Checks wheather the file exists prior to try and access it
#
function check
{
if [ ! -e "$1" ]
then
echo "I could not find the specified file: $1"
exit
fi
}
# Now this is where the script executions begins
# If the user gave more than 2 args, OR pass the -h arg OR the --help arg OR no args at all run usage
# to show user the proper way to call the script
if [ "$#" -gt 2 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ] || [ "$#" -lt 1 ]; then
usage
fi
# Use getopts to process the args, -b and -r need additional arguments
while getopts ":r:b:b" opt; do
# If -b passed run below
case $opt in
b)
check $OPTARG
backup $OPTARG #Backup all files listed in $OPTARG
compress #Compress the saved files
moveIt #Move the file to current directory
clean #Clean the mess in $tmp
;;
# -r passed run below
r)
check $OPTARG
extract $OPTARG
restore
clean
;;
# Invalid arg run usage
*)
usage
;;
esac
done
exit
view raw configBackup.sh hosted with ❤ by GitHub