Cron y crontab: el programador de tareas de linux

Crontab, la lista de tareas.

Crontab se trata archivo de texto que guarda la lista de comandos a ejecutar en un momento determinado.

Estos comando siempre se lanzan en background, así que no habrá interacción con el usuario.

Crontab comprueba la fecha y hora en que se debe ejecutar el script o el comando, los permisos de ejecución y lo realizará en el background.

Cada usuario puede tener su propio archivo crontab, de hecho el /etc/crontab se asume que es el archivo crontab del usuario root, cuando los usuarios normales (e incluso root) desean generar su propio archivo de crontab, entonces utilizaremos el comando crontab.

Veamos un ejemplo sencillo.

Vamos a automatizar la limpieza de archivos temporales que genera un servidor web en nuestro sistema, estos archivos se encuentran en la carpeta “tmp” del usuario administrador del servidor web, supongamos que nuestro usuario es “admin” y la ruta completa será “/home/admin/tmp”, los archivos tienen la forma “sess_4abmmo96i9m2uhb364kc7sq181” así que podemos considerar que haciendo un “rm sess_*” se borrarán todos, no obstante vamos a borrar sólo los ficheros que tengan más de 24 horas.

Para este menester existe una opción más aconsejable como es el “systemd” pero el resultado será el mismo.

Vamos a automatizar la actualización de un sistema, para eliminar la molesta de “siempre tengo que andar actualizando y eso no me gusta!”.

Primero que nada haremos un script. Este script será llamado por cron y contendrá todas las instrucciones que queremos que haga, por lo tanto es necesario probarlo en varios casos y de varias formas antes de incluirlo a cron, un sencillo script de actualizacion como este:

#!/bin/bash
#script ejemplo de actualizacion
#elija su distribucion
#debian-ubuntu
#apt-get update & apt-get -y upgrade
#fedora
#yum -y update
#Arch
#pacman –noconfirm -Syu
Quitale el # a la línea de tu distro. En caso de que sea Ubuntu/Debian, a la que empieza con apt-get.

Guardamos el script como actualizacion.sh (ej. directorio scripts tu home). Cambiamos los permisos de ejecucion del dichoso script con:

chmod a+x ~/scripts/actualizacion.sh
Ejecutamos el script un par de veces para verificar que todo ejecute sin problemas, modificamos lo necesario (no debe contener errores, si no cron solo repetira un error una y otra vez). Ahora a agregar la tarea a nuestro crontab.

Agregar tareas a crontab

Ejecutamos la edición del crontab con crontab -e, en algunas distros (como ubuntu) nos da la opcion de elegir el editor de textos que deseemos, los demás nos quedamos con vi. El archivo crontab lucirá algo asi.

# m h dom mon dow user command
donde:

m corresponde al minuto en que se va a ejecutar el script, el valor va de 0 a 59
h la hora exacta, se maneja el formato de 24 horas, los valores van de 0 a 23, siendo 0 las 12:00 de la medianoche.
dom hace referencia al día del mes, por ejemplo se puede especificar 15 si se quiere ejecutar cada dia 15
dow significa el día de la semana, puede ser numérico (0 a 7, donde 0 y 7 son domingo) o las 3 primeras letras del día en inglés: mon, tue, wed, thu, fri, sat, sun.
user define el usuario que va a ejecutar el comando, puede ser root, u otro usuario diferente siempre y cuando tenga permisos de ejecución del script.
command refiere al comando o a la ruta absoluta del script a ejecutar, ejemplo: /home/usuario/scripts/actualizar.sh, si acaso llama a un script este debe ser ejecutable
Para que quedara claro unos cuantos ejemplos de tareas de cron explicados:

15 10 * * * usuario /home/usuario/scripts/actualizar.sh
Ejecutará el script actualizar.sh a las 10:15 a.m. todos los días

15 22 * * * usuario /home/usuario/scripts/actualizar.sh
Ejecutará el script actualizar.sh a las 10:15 p.m. todos los días

00 10 * * 0 root apt-get -y update Usuario root
Ejecutará una actualización todos los domingos a las 10:00 a.m

45 10 * * sun root apt-get -y update
Usuario root ejecutará una actualización todos los domingos (sun) a las 10:45 a.m

30 7 20 11 * usuario /home/usuario/scripts/actualizar.sh
El día 20 de noviembre a las 7:30 el usuario correra el script

30 7 11 11 sun usuario /home/usuario/scripts/pastel_con_velitas.sh
El día 11 de noviembre a las 7:30 a.m. y que sea domingo, el usuario festejará su sysadmin (o sea a mí)

01 * * * * usuario /home/usuario/scripts/molestorecordatorio.sh
Un molesto recordatorio cada minuto de cada hora todos los días (NO recomendable).

Igual se pueden manejar rangos especiales:

30 17 * * 1,2,3,4,5
A las 5:30 de la tarde todos los días de lunes a viernes.

00 12 1,15,28 * *
A las 12 del día todos los días primero, quince y 28 de cada mes (ideal para nóminas)

Si esto resulta confuso, crontab maneja cadenas especiales para definir estos rangos.

@reboot Ejecuta una vez, al inicio
@yearly ejecuta sólo una vez al año: 0 0 1 1 *
@annually igual que @yearly
@monthly ejecuta una vez al mes, el día primero: 0 0 1 * *
@weekly Semanal el primer minuto de la primer hora de la semana. 0 0 * * 0″.
@daily diario, a las 12:00A.M. 0 0 * * *
@midnight igual que @daily
@hourly al primer minuto de cada hora: 0 * * * *

Su uso es muy sencillo.

@hourly usuario /home/usuario/scripts/molestorecordatorio.sh
@monthly usuario /home/usuario/scripts/respaldo.sh
@daily root apt-get update && apt-get -y upgrade
Por último y no menos importante:

Administracion de trabajos en cron

crontab archivo
Remplaza el existente archivo crontab con un archivo definido por el usuario

crontab -e
Editar el archivo crontab del usuario, cada linea nueva sera una nueva tarea de crontab.

crontab -l
Lista todas las tareas de crontab del usuario

crontab -d
Borra el crontab del usuario

crontab -c dir
Define el directoriod e crontab del usuario (este debe tener permisos de escritura y ejecucion del usuario)

crontab -u usuario
prefijo para manejar el crontab de otro usuario, ejemplos:

$ sudo crontab -l -u root
$ sudo crontab -e usuario2
#crontab -d -u usuario
Esta herramienta, como muchas otras se pueden ver a mas profundidad y con mas detalle en:

tar ejemplos para comprimir y descomprimir archivos

1. Crear “tar” Fichero de Archivos

The below example command will create a tar archive file tecmint-14-09-12.tar for a directory /home/tecmint in current working directory. See the example command in action.

# tar -cvf tecmint-14-09-12.tar /home/tecmint/
 /home/tecmint/
 /home/tecmint/cleanfiles.sh
 /home/tecmint/openvpn-2.1.4.tar.gz
 /home/tecmint/tecmint-14-09-12.tar
 /home/tecmint/phpmyadmin-2.11.11.3-1.el5.rf.noarch.rpm
 /home/tecmint/rpmforge-release-0.5.2-2.el5.rf.i386.rpm

Let’s discuss the each option we have used in the above command for creating tar archive file.

c – Creates a new .tar archive file.
v – Verbosely show the .tar file progress.
f – File name type of the archive file.

2. Crear “tar.gz” Fichero de Archivos Comprimidos

To create a compressed gzip archive file we use the option as z. For example the below command will create a compressed MyImages-14-09-12.tar.gz file for the directory /home/MyImages. (Note : tar.gz and tgz both are similar).

# tar cvzf MyImages-14-09-12.tar.gz /home/MyImages
OR
# tar cvzf MyImages-14-09-12.tgz /home/MyImages
/home/MyImages/
/home/MyImages/Sara-Khan-and-model-Priyanka-Shah.jpg
/home/MyImages/RobertKristenviolent101201.jpg
/home/MyImages/Justintimerlake101125.jpg
/home/MyImages/Mileyphoto101203.jpg
/home/MyImages/JenniferRobert101130.jpg
/home/MyImages/katrinabarbiedoll231110.jpg
/home/MyImages/the-japanese-wife-press-conference.jpg
/home/MyImages/ReesewitherspoonCIA101202.jpg
/home/MyImages/yanaguptabaresf231110.jpg
3. Create tar.bz2 Archive File

The bz2 feature compress and create archive file less than the size of the gzip. The bz2 compression takes more time to compress and decompress files as compared to gzip which takes less time. To create highly compressed tar file we use option as j. The following example of command will create a Phpfiles-org.tar.bz2 file for a directory /home/php. (Note: tar.bz2 and tbz is similar as tb2).

# tar cvfj Phpfiles-org.tar.bz2 /home/php
OR
# tar cvfj Phpfiles-org.tar.tbz /home/php
OR
# tar cvfj Phpfiles-org.tar.tb2 /home/php
/home/php/
/home/php/iframe_ew.php
/home/php/videos_all.php
/home/php/rss.php
/home/php/index.php
/home/php/vendor.php
/home/php/video_title.php
/home/php/report.php
/home/php/object.html
/home/php/video.php
4. Untar tar Archive File

To untar or extract a tar file, just issue following command using option x (extract). For example the below command will untar the file public_html-14-09-12.tar in present working directory. If you want untar in a different directory then use option as -C (specified directory).

## Untar files in Current Directory ##
# tar -xvf public_html-14-09-12.tar
## Untar files in specified Directory ##
# tar -xvf public_html-14-09-12.tar -C /home/public_html/videos/
/home/public_html/videos/
/home/public_html/videos/views.php
/home/public_html/videos/index.php
/home/public_html/videos/logout.php
/home/public_html/videos/all_categories.php
/home/public_html/videos/feeds.xml
5. Uncompress tar.gz Archive File

To Uncompress tar.gz archive file, just run following command. If would like to untar in different directory just use option -C and the path of the directory, like we shown in the above example.

# tar -xvf thumbnails-14-09-12.tar.gz
/home/public_html/videos/thumbnails/
/home/public_html/videos/thumbnails/katdeepika231110.jpg
/home/public_html/videos/thumbnails/katrinabarbiedoll231110.jpg
/home/public_html/videos/thumbnails/onceuponatime101125.jpg
/home/public_html/videos/thumbnails/playbutton.png
/home/public_html/videos/thumbnails/ReesewitherspoonCIA101202.jpg
/home/public_html/videos/thumbnails/snagItNarration.jpg
/home/public_html/videos/thumbnails/Minissha-Lamba.jpg
/home/public_html/videos/thumbnails/Lindsaydance101201.jpg
/home/public_html/videos/thumbnails/Mileyphoto101203.jpg
6. Uncompress tar.bz2 Archive File

To Uncompress highly compressed tar.bz2 file, just use the following command. The below example command will untar all the .flv files from the archive file.

# tar -xvf videos-14-09-12.tar.bz2
/home/public_html/videos/flv/katrinabarbiedoll231110.flv
/home/public_html/videos/flv/BrookmuellerCIA101125.flv
/home/public_html/videos/flv/dollybackinbb4101125.flv
/home/public_html/videos/flv/JenniferRobert101130.flv
/home/public_html/videos/flv/JustinAwardmovie101125.flv
/home/public_html/videos/flv/Lakme-Fashion-Week.flv
/home/public_html/videos/flv/Mileyphoto101203.flv
/home/public_html/videos/flv/Minissha-Lamba.flv
7. List Content of tar Archive File

To list the content of tar archive file, just run the following command with option t (list content). The below command will list the content of uploadprogress.tar file.

# tar -tvf uploadprogress.tar
-rw-r–r– chregu/staff 2276 2011-08-15 18:51:10 package2.xml
-rw-r–r– chregu/staff 7877 2011-08-15 18:51:10 uploadprogress/examples/index.php
-rw-r–r– chregu/staff 1685 2011-08-15 18:51:10 uploadprogress/examples/server.php
-rw-r–r– chregu/staff 1697 2011-08-15 18:51:10 uploadprogress/examples/info.php
-rw-r–r– chregu/staff 367 2011-08-15 18:51:10 uploadprogress/config.m4
-rw-r–r– chregu/staff 303 2011-08-15 18:51:10 uploadprogress/config.w32
-rw-r–r– chregu/staff 3563 2011-08-15 18:51:10 uploadprogress/php_uploadprogress.h
-rw-r–r– chregu/staff 15433 2011-08-15 18:51:10 uploadprogress/uploadprogress.c
-rw-r–r– chregu/staff 1433 2011-08-15 18:51:10 package.xml
8. List Content tar.gz Archive File

Use the following command to list the content of tar.gz file.

# tar -tvf staging.tecmint.com.tar.gz
-rw-r–r– root/root 0 2012-08-30 04:03:57 staging.tecmint.com-access_log
-rw-r–r– root/root 587 2012-08-29 18:35:12 staging.tecmint.com-access_log.1
-rw-r–r– root/root 156 2012-01-21 07:17:56 staging.tecmint.com-access_log.2
-rw-r–r– root/root 156 2011-12-21 11:30:56 staging.tecmint.com-access_log.3
-rw-r–r– root/root 156 2011-11-20 17:28:24 staging.tecmint.com-access_log.4
-rw-r–r– root/root 0 2012-08-30 04:03:57 staging.tecmint.com-error_log
-rw-r–r– root/root 3981 2012-08-29 18:35:12 staging.tecmint.com-error_log.1
-rw-r–r– root/root 211 2012-01-21 07:17:56 staging.tecmint.com-error_log.2
-rw-r–r– root/root 211 2011-12-21 11:30:56 staging.tecmint.com-error_log.3
-rw-r–r– root/root 211 2011-11-20 17:28:24 staging.tecmint.com-error_log.4
9. List Content tar.bz2 Archive File

To list the content of tar.bz2 file, issue the following command.

# tar -tvf Phpfiles-org.tar.bz2
drwxr-xr-x root/root 0 2012-09-15 03:06:08 /home/php/
-rw-r–r– root/root 1751 2012-09-15 03:06:08 /home/php/iframe_ew.php
-rw-r–r– root/root 11220 2012-09-15 03:06:08 /home/php/videos_all.php
-rw-r–r– root/root 2152 2012-09-15 03:06:08 /home/php/rss.php
-rw-r–r– root/root 3021 2012-09-15 03:06:08 /home/php/index.php
-rw-r–r– root/root 2554 2012-09-15 03:06:08 /home/php/vendor.php
-rw-r–r– root/root 406 2012-09-15 03:06:08 /home/php/video_title.php
-rw-r–r– root/root 4116 2012-09-15 03:06:08 /home/php/report.php
-rw-r–r– root/root 1273 2012-09-15 03:06:08 /home/php/object.html
10. Untar Single file from tar File

To extract a single file called cleanfiles.sh from cleanfiles.sh.tar use the following command.

# tar -xvf cleanfiles.sh.tar cleanfiles.sh
OR
# tar –extract –file=cleanfiles.sh.tar cleanfiles.sh
cleanfiles.sh
11. Untar Single file from tar.gz File

To extract a single file tecmintbackup.xml from tecmintbackup.tar.gz archive file, use the command as follows.

# tar -zxvf tecmintbackup.tar.gz tecmintbackup.xml
OR
# tar –extract –file=tecmintbackup.tar.gz tecmintbackup.xml
tecmintbackup.xml
12. Untar Single file from tar.bz2 File

To extract a single file called index.php from the file Phpfiles-org.tar.bz2 use the following option.

# tar -jxvf Phpfiles-org.tar.bz2 home/php/index.php
OR
# tar –extract –file=Phpfiles-org.tar.bz2 /home/php/index.php
/home/php/index.php
13. Untar Multiple files from tar, tar.gz and tar.bz2 File

To extract or untar multiple files from the tar, tar.gz and tar.bz2 archive file. For example the below command will extract “file 1” “file 2” from the archive files.

# tar -xvf tecmint-14-09-12.tar “file 1” “file 2”
# tar -zxvf MyImages-14-09-12.tar.gz “file 1” “file 2”
# tar -jxvf Phpfiles-org.tar.bz2 “file 1” “file 2”
14. Extract Group of Files using Wildcard

To extract a group of files we use wildcard based extracting. For example, to extract a group of all files whose pattern begins with .php from a tar, tar.gz and tar.bz2 archive file.

# tar -xvf Phpfiles-org.tar –wildcards ‘*.php’
# tar -zxvf Phpfiles-org.tar.gz –wildcards ‘*.php’
# tar -jxvf Phpfiles-org.tar.bz2 –wildcards ‘*.php’
/home/php/iframe_ew.php
/home/php/videos_all.php
/home/php/rss.php
/home/php/index.php
/home/php/vendor.php
/home/php/video_title.php
/home/php/report.php
/home/php/video.php
15. Add Files or Directories to tar Archive File

To add files or directories to existing tar archived file we use the option r (append). For example we add file xyz.txt and directory php to existing tecmint-14-09-12.tar archive file.

# tar -rvf tecmint-14-09-12.tar xyz.txt
# tar -rvf tecmint-14-09-12.tar php
drwxr-xr-x root/root 0 2012-09-15 02:24:21 home/tecmint/
-rw-r–r– root/root 15740615 2012-09-15 02:23:42 home/tecmint/cleanfiles.sh
-rw-r–r– root/root 863726 2012-09-15 02:23:41 home/tecmint/openvpn-2.1.4.tar.gz
-rw-r–r– root/root 21063680 2012-09-15 02:24:21 home/tecmint/tecmint-14-09-12.tar
-rw-r–r– root/root 4437600 2012-09-15 02:23:41 home/tecmint/phpmyadmin-2.11.11.3-1.el5.rf.noarch.rpm
-rw-r–r– root/root 12680 2012-09-15 02:23:41 home/tecmint/rpmforge-release-0.5.2-2.el5.rf.i386.rpm
-rw-r–r– root/root 0 2012-08-18 19:11:04 xyz.txt
drwxr-xr-x root/root 0 2012-09-15 03:06:08 php/
-rw-r–r– root/root 1751 2012-09-15 03:06:08 php/iframe_ew.php
-rw-r–r– root/root 11220 2012-09-15 03:06:08 php/videos_all.php
-rw-r–r– root/root 2152 2012-09-15 03:06:08 php/rss.php
-rw-r–r– root/root 3021 2012-09-15 03:06:08 php/index.php
-rw-r–r– root/root 2554 2012-09-15 03:06:08 php/vendor.php
-rw-r–r– root/root 406 2012-09-15 03:06:08 php/video_title.php
16. Add Files or Directories to tar.gz and tar.bz2 files

The tar command don’t have a option to add files or directories to a existing compressed tar.gz and tar.bz2 archive file. If we do try will get tbe following error.

# tar -rvf MyImages-14-09-12.tar.gz xyz.txt
# tar -rvf Phpfiles-org.tar.bz2 xyz.txt
tar: This does not look like a tar archive
tar: Skipping to next header
xyz.txt
tar: Error exit delayed from previous errors
17. How To Verify tar, tar.gz and tar.bz2 Archive File

To verfify any tar or compressed archived file we use option as W (verify). To do, just use the following examples of command. (Note : You cannot do verification on a compressed ( *.tar.gz, *.tar.bz2 ) archive file).

# tar tvfW tecmint-14-09-12.tar
tar: This does not look like a tar archive
tar: Skipping to next header
tar: Archive contains obsolescent base-64 headers
tar: VERIFY FAILURE: 30740 invalid headers detected
Verify -rw-r–r– root/root 863726 2012-09-15 02:23:41 /home/tecmint/openvpn-2.1.4.tar.gz
Verify -rw-r–r– root/root 21063680 2012-09-15 02:24:21 /home/tecmint/tecmint-14-09-12.tar
tar: /home/tecmint/tecmint-14-09-12.tar: Warning: Cannot stat: No such file or directory
Verify -rw-r–r– root/root 4437600 2012-09-15 02:23:41 home/tecmint/phpmyadmin-2.11.11.3-1.el5.rf.noarch.rpm
tar: /home/tecmint/phpmyadmin-2.11.11.3-1.el5.rf.noarch.rpm: Warning: Cannot stat: No such file or directory
Verify -rw-r–r– root/root 12680 2012-09-15 02:23:41 home/tecmint/rpmforge-release-0.5.2-2.el5.rf.i386.rpm
tar: /home/tecmint/rpmforge-release-0.5.2-2.el5.rf.i386.rpm: Warning: Cannot stat: No such file or directory
Verify -rw-r–r– root/root 0 2012-08-18 19:11:04 xyz.txt
Verify drwxr-xr-x root/root 0 2012-09-15 03:06:08 php/
18. Check the Size of the tar, tar.gz and tar.bz2 Archive File

To check the size of any tar, tar.gz and tar.bz2 archive file, use the following command. For example the below command will display the size of archvie file in Kilobytes (KB).

# tar -czf – tecmint-14-09-12.tar | wc -c
12820480
# tar -czf – MyImages-14-09-12.tar.gz | wc -c
112640
# tar -czf – Phpfiles-org.tar.bz2 | wc -c
20480
Tar Usage and Options

c – create a archive file.
x – extract a archive file.
v – show the progress of archive file.
f – filename of archive file.
t – viewing content of archive file.
j – filter archive through bzip2.
z – filter archive through gzip.
r – append or update files or directories to existing archive file.
W – Verify a archive file.
wildcards – Specify patters in unix tar command.
That’s it for now, hope the above tar command examples are enough for you to learn and for more information please use man tar command.

rsync + sshpass: copias de seguridad remotas

Veamos como crear un script para realizar una copia de seguridad remota entre dos servidores.

Supongamos que tenemos dos servidores remotos uno que llamaremos “producción” y otro que llamaremos “backup”, ambos están corriendo el mismo sistema operativo Linux, una versión CentOS 7 . La idea es crear un script sobre el servidor “producción” que se ejecutará mediante un “crontab” todas las noches, ese escript realizará una copia de los archivos de una determinada carpeta y además necesitamos realizar la copia de la base de datos de un determinado usuario de MySQL. Por otro lado tenemos una unidad NAS en la red local del servidor donde realizaremos una copia semanal del servidor de backup. Veamos el siguiente esquema para terminar de entender el problema que planteamos:

Para poder desarrollar esta solución tenemos que tener instalados estos tres programas:

  • rsync: que será el programa principal que realizará las copias
  • sshpass: necesario para poder hacer la validación automática del usuario, ya que la idea del script es que se ejecute de forma auomática por la noche, para ser lanzado desde un crontab, y teniendo en cuenta que rsync no para poder hacer la copia remota siempre nos pedirá el usuario y la contraseña del servidor remoto, es por lo que necesitamos de la ayuda de sshpass para poder hacer la validación.
  • ftp: el cliente de ftp realizará la copia de seguridad del servidor Backup a la unidad NAS.
yum install ftp sshpass rsync

Creando ficheros de respaldo

Lo primero que haremos es un script para crear un fichero que incluya un “mysqldump” para cada una de las bases de datos que queramos respaldar:

#!/bin/bash
mysqldump --user=usuario1 --password=pwdusuario1 nombre-bbdd > /ruta-de-la/copia/bbddusuario1.sql
mysqldump --user=usuario2 --password=pwdusuario2 nombre-bbdd > /ruta-de-la/copia/bbddusuario2.sql
...
mysqldump --user=usuariox --password=pwdusuariox nombre-bbdd > /ruta-de-la/copia/bbddusuariox.sql

Si quisieramos copiar todas las bases de datos con una única instrucción:

#!/bin/bash
mysqldump --user=root --password=pwddelroot --all-databases > /ruta-de-la/copia/todotodotodo.sql

Por último si queremos tener un fichero por cada una de las bases de datos y para cada día, también podemos realizarlo de esta manera más elegante.

#! /bin/bash 
TIMESTAMP=$(date +"%F")
BACKUP_DIR="/ruta-de-la/copia/$TIMESTAMP"
MYSQL_USER="root"
MYSQL=/usr/bin/mysql
MYSQL_PASSWORD="passwordroot"
MYSQLDUMP=/usr/bin/mysqldump
 
mkdir -p "$BACKUP_DIR/mysql"
 
databases=`$MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)"`
 
for db in $databases; do
  $MYSQLDUMP --force --opt --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db | gzip > "$BACKUP_DIR/mysql/$db.gz"
done

Comprimir archivos

Luego para ahorrar espacio y hacer que la transmisión sea más rápida ahorrando ancho de banda, comprimiremos dichos archivos.

#!/bin/bash
tar cvzf /ruta-de-la/copia/CopiaTotal.tgz /ruta-de-la/copia/

Si queremos más compresión a cambio de más procesador para comprimir y descomprimir podemos utilizar el algoritmo bz2 (tar.bz2=tbz=tb2):

#!/bin/bash
tar cvfj /ruta-de-la/copia/CopiaTotal.tar.bz2 /ruta-de-la/copia/

Ahora enviamos los archivos:

rsync -avzh --rsh="/usr/bin/sshpass -p claveusuarioremoto ssh -l usuarioremoto" /ruta-de-la/copia/*  ip-maquina-remota:/ruta-del/backup

 

Restaurar base de datos

mysql --user=nombreusuerbbdd --password=pwduserbbdd nombre_bbdd < /ruta-de-la/copia/archivo_dump.SQL