Linux - Remote Backups with rsync
What is rsync?
rsync
is a command-line utility for synchronizing files and directories between two locations. It can handle local backups or remote synchronization over SSH, ensuring that your data is consistently updated and accessible.
Why Use rsync for Backups?
Incremental Backups: Only the changes in files are synced.
Bandwidth Efficient: Uses minimal bandwidth by syncing only differences.
Versatile: Can sync both local and remote files.
Preserves File Permissions: Maintains file permissions, ownership, timestamps, etc.
Secure: Can be used with SSH for secure file transfer.
Checking for rsync Installation
Before diving into its usage, let's check if rsync
is installed on your system:
rsync --version
If it’s not installed, you can quickly set it up with the following commands:
sudo apt update
sudo apt install rsync
Basic Usage of rsync
Understanding the basic syntax of rsync
is essential before automating your backup process:
rsync [options] source destination
For example, to back up your documents from the /home/user/documents
directory to an external media location, you can use:
rsync -av /home/user/documents /media/backup
-a
stands for "archive" mode, which preserves permissions, timestamps, symbolic links, etc.-v
is for "verbose," which displays the process of syncing files.
Remote Backups Using SSH
Step 1: Generate SSH Key Pair
To enable passwordless authentication, first generate an SSH key pair on your local machine:
ssh-keygen
This will create two files: a private key (~/.ssh/id_rsa
) and a public key (~/.ssh/id_
rsa.pub
).
Step 2: Copy the Public SSH Key
Display the contents of your public SSH key on the local machine:
cat ~/.ssh/id_rsa.pub
This will output your public key. Copy the entire output.
Step 3: Add Your Public Key to the Remote Server
Now, log in to the remote server > Paste the public key in the authorized_keys
file.
Step 4: Test the SSH Connection
Then, try logging back into the remote server from the local machine without entering a password:
ssh user@172.31.13.54
If you successfully log in without a password prompt, your SSH key setup is working.
Step 5: Using rsync for Remote Backups
You can now use rsync
to perform remote backups. Here's an example rsync
command to sync a directory from the local machine to the remote server:
rsync -avz /local/path/to/backup/ user@172.31.13.54:backup/
-a
: Archive mode (preserves permissions, symbolic links, etc.).-v
: Verbose (shows detailed output).-z
: Compression (compresses data during transfer).
Be sure to replace /local/path/to/backup/
with the actual directory you wish to back up and backup/
with the desired destination path on the remote server.
Conclusion
Using rsync
for backups streamlines the process of keeping your data secure, whether locally or remotely. By following these simple steps, you can ensure that your important files are backed up efficiently and reliably. Happy backing up!