📜  rsync with ssh key - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:19:51.625000             🧑  作者: Mango

Rsync with SSH Key

Introduction

Rsync is a powerful tool for synchronizing files between servers. It allows copying only the differences between files, which makes it an efficient way of keeping files in sync. When combined with SSH key authentication, it ensures secure and quick transfer of files between servers.

In this tutorial, we will cover how to use rsync with SSH key authentication to copy files between servers.

Prerequisites

This tutorial assumes that you have two remote servers (server1 and server2), both running Linux. You also need to have SSH key authentication set up for the user you will be connecting with.

Steps
Step 1: Create the SSH Key

If you don't already have an SSH key set up for the user, you need to create one. You can do this by running the following command:

$ ssh-keygen

Follow the prompts to generate a new SSH key.

Step 2: Copy the Public Key to the Remote Server

Once you have an SSH key, you need to copy the public key to the remote server(s) you want to connect to. You can do this by running the following command:

$ ssh-copy-id user@server2

This will copy the public key to the authorized_keys file on the remote server, allowing you to log in without a password.

Step 3: Test the SSH Connection

Before using rsync, test the SSH connection to make sure it is working. You can do this by running the following command:

$ ssh user@server2

If the connection is successful, you should be logged in to server2 without a password prompt.

Step 4: Use Rsync to Synchronize Files

Once you have set up SSH key authentication, you can use rsync to synchronize files between servers. The basic syntax for rsync is as follows:

$ rsync [options] source destination

For example, to copy the contents of /var/www on server1 to /var/www on server2, you can run the following command:

$ rsync -avz -e "ssh" /var/www user@server2:/var/

Here, the -avz options enable archive mode, verbose output, and compression. The -e option specifies the SSH command to use for the transfer.

Step 5: Schedule Regular Synchronization

If you need to keep files synchronized between servers on a regular basis, you can create a cron job to run the rsync command at defined intervals. For example, to run the rsync command every hour, add the following line to your crontab file:

0 * * * * rsync -avz -e "ssh" /var/www user@server2:/var/
Conclusion

Using rsync with SSH key authentication allows you to securely and efficiently synchronize files between remote servers. By following the steps in this tutorial, you should now be able to set up rsync with SSH key authentication and schedule regular synchronizations using cron.