backups: rsync, cron, ssh

I recently realized that I could use my server’s storage without needing fancy Docker containers or GUIs to move files. That’s when I discovered rsync.

Rsync is better than other cp tools because it only copies the differences between files. It’s a very simple program that transfers files over SSH. The simplest usage looks like this:

rsync /source /destination

To copy a file to a remote server:

rsync /source username@address:/destination

Wait! Before you copy anything… I strongly recommend using the --dry-run (-n) and --verbose (-v) flags first to ensure your paths are correct. For example, when copying folders (with -r or -a), it’s easy to accidentally add or omit a / at the end of a path. Without the trailing /, you might copy the folder itself instead of just its contents—or worse, overwrite months of backups with an empty folder! :D So don’t be lazy: use --dry-run.

About the Archive (-a) flag:

  • -r: Synchronize folders recursively (includes subfolders).
  • -l: Preserves symlinks.
  • -p: Preserves file permissions.
  • -t: Preserves modification times.
  • -g: Preserves group ownership.
  • -o: Preserves owner of files.
  • -D: Allows rsync to transfer device and special files.

Basically, if you need a copy with all the metadata intact, just use -a.

Setting up Passwordless Login Before moving on, you should set up passwordless SSH login. Without it, the next part of this guide won’t be very useful.

  1. Create a user on the server (if you haven’t already):
    sudo adduser username
    
  2. Add them to the sudo group:
    sudo usermod -aG sudo username
    
  3. Check if you have SSH keys on your machine:
    ls -al ~/.ssh/id_*.pub
    
  4. If not, generate them:
    ssh-keygen -t ed25519
    
  5. Finally, copy the key to the server:
    ssh-copy-id remote_username@server_address
    

For better security, I recommend changing these settings in /etc/ssh/sshd_config:

PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no

Automating with Crontab Now we can automate our backups using crontab. It’s a simple tool that runs scripts at specific intervals. To edit your schedule, use: crontab -e.

The syntax is:

* * * * * /path/to/yourScript

The stars stand for: Minute (0-59), Hour (0-23), Day of month (1-31), Month (1-12), and Day of week (0-6, starting Sunday).

For example, to run a script every 12 minutes:

*/12 * * * * /path/to/yourScript

You can learn more by checking the man pages or using tools like crontab.guru.

Today we covered the basics of rsync and crontab. Honestly, I don’t know why I didn’t realize sooner how easy it is to transfer files to a remote server!