1. Home
  2. Knowledge Base
  3. How to Copy Files Over SSH Using rsync

How to Copy Files Over SSH Using rsync

In this guide, we’ll demonstrate how to securely copy files from one server to another using rsync over SSH. This is an efficient and secure method of syncing files, often used for backups, migrations, or automated tasks.

Prerequisites

  • SSH access enabled on both servers.
  • rsync installed on both servers.
  • Root privileges or sudo access.

Step 1: Install rsync (if not already installed)

On both servers:

For Debian/Ubuntu

# apt install rsync -y

For CentOS/RHEL/AlmaLinux

# yum install rsync -y

Step 2: Set Up SSH Key-Based Authentication

To avoid entering the password each time you use rsync, set up SSH key-based authentication from Source VM to Destination VM.

2.1 Generate an SSH key pair on source-vm:

# ssh-keygen -t rsa -b 4096 -C "rsync-ssh-key"
  • Press Enter to accept the default path (/root/.ssh/id_rsa).
  • Leave the passphrase empty if you want passwordless authentication.

2.2 Copy the public key to destination-vm:

# ssh-copy-id root@destination-vm
  • This adds your public key (id_rsa.pub) to the remote server’s ~/.ssh/authorized_keys file.

2.3 Test SSH login:

# ssh root@destination-vm

You should be able to log in without a password.

Step 3: Basic rsync Syntax Over SSH

# rsync -avz -e ssh /path/to/source-directory/ root@destination-vm:/path/to/destination-directory/

Options Explained:

  • -a: Archive mode (preserves file permissions, timestamps, symbolic links)
  • -v: Verbose output
  • -z: Compress files during transfer
  • -e ssh: Use SSH as the transport

Example – Copy a Directory

To copy /var/www/html from source-vm to /var/www/backup/ on destination-vm:

# rsync -avz -e ssh /var/www/html/ root@destination-vm:/var/www/backup/

The trailing slash (/) on the source path copies contents of the directory. Without the slash, it copies the directory itself.

Optional – Dry Run Before Execution

To preview the files that will be transferred:

# rsync -avz --dry-run -e ssh /var/www/html/ root@destination-vm:/var/www/backup/

Automate with Cron

Create a cron job on source-vm to run rsync at scheduled intervals:

# crontab -e

Example to run daily at 2 AM:

0 2 * * * rsync -avz -e ssh /var/www/html/ root@destination-vm:/var/www/backup/ >> /var/log/rsync.log 2>&1

Troubleshooting

  • Permission denied: Ensure SSH keys are set up correctly and have proper permissions.
  • Connection refused: Make sure the SSH service is running on destination-vm.
  • Path errors: Confirm source and destination directories exist or use –rsync-path to create them remotely.

Conclusion

By combining SSH key-based authentication and rsync, you can automate and secure file transfers between servers with minimal effort. Whether you’re migrating data or setting up nightly backups, this method is fast, reliable, and efficient.

Was this article helpful?