Fri. Aug 7th, 2020

How to scheduled backups between Linux hosts using scp

2 min read

You can use rsync backup methods, but it is relatively complicated to set up and use, and if you only back up a small part, such as just backing up the MySQL database, there is no need to use rsync software backup. On both Linux hosts, and both have ssh permissions, it is recommended to use the scp command for the backup. This backup is the fast and encrypted transmission and has high security.

How to scheduled backups between Linux hosts using scp

First, scp needs password authentication to establish a connection, so our first step is to add the ssh public key.

ssh-keygen -t rsa

This command will generate two files (id_rsa, id_rsa.pub) in the user directory ~/.ssh/.

The second is to copy the id_rsa.pub file on the local (192.168.1.33) host to the .ssh directory in the root user’s home directory of the remote Linux (192.168.1.44) host and rename the authorized_keys file.

scp /root/.ssh/id_rsa.pub root@192.168.1.44:/root/.ssh/authorized_keys

In this way, using the scp command on the local Linux (192.168.1.33) host to copy files to the remote Linux host (192.168.1.44) will not prompt for a password, and directly copy.

Third, put the command into a script, such as the following script example (please modify according to your specific situation)

#!/bin/sh
backpath=/var/ftp/backup/
date=`date +%y%m%d`
site=sitename
tar zcf ${backpath}${site}”-“${date}.tar.gz /var/www/${site}
scp ${backpath}${site}”-“${date}.tar.gz root@backupserver:/var/backup
find ${backpath} -mtime +30 -exec rm {} \;

Note: You can use the crontab command to run the script at regular intervals.