How to set up Rsync to transfer files between servers over SSH

Rsync is a tool for transferring and synchronizing files across networked computers by comparing the modification times and sizes of files. Rsync is written in C as a single-threaded application. If you want to save a copy/backup of your files on different machines, you can set up a cron job using Rsync. In this post, I will show the steps to set up SSH keys and then use Rsync over SSH to transfer files from one machine to another machine.

  • Create the SSH key pair on the client machine using the following command. If you do not create an SSH key pair, you need to type your server’s password whenever you run Rsync.
ssh-keygen -t rsa

After running the above command, public and private keys will be generated. The public key will be stored in /home/user/.ssh/ The private key (identification) will be stored in /home/user/.ssh/id_rsa.

  • Copy the public key on the server using the following command:
ssh-copy-id -i /home/user/.ssh/ root@server_ip -p server_port

You will be prompted to type the password of the server and then the public key will be copied on the server machine.

  • Create a new file and copy the following codes to pull data from server to client. (e.g. vi v-user-rsync-alldata)

CLIENT_BACKUP_DIR="/backup_directory"  # The directory on client where you want to keep backups
SERVER_DIR="/files_directory/"	# The directory on server which you want to copy

# Rsync data from server to client
echo "Pulling backups from the main server..."

rsync --delete --progress -vae "ssh -p $SERVER_PORT" $SERVER_USER@$SERVER_IP:$SERVER_DIR $CLIENT_BACKUP_DIR

echo "Backup Completed..."
  • Run rsync using the following command:
bash file_name (e.g. bash v-user-rsync-alldata)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.