Skip to content

Instantly share code, notes, and snippets.

@faizalmansor
Last active April 15, 2024 22:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save faizalmansor/aa3805d2341bcb64f0476892a6024732 to your computer and use it in GitHub Desktop.
Save faizalmansor/aa3805d2341bcb64f0476892a6024732 to your computer and use it in GitHub Desktop.
Backup To Remote Server over SSH

Backup To Remote Server over SSH

Background Info

  • Server A: Production Server, Example IP: 192.168.0.41
  • Server B: Backup Server, Example IP: 192.168.0.51

Overview

Backup a folder in Server A and send tarred file to Server B

Step 1: Setup SSH Public Key Based Authentication

In Server A, generate key

ssh-keygen -t rsa

Press [enter] key twice to avoid creating a passphrase. It will create 2 files in ~/.ssh directory as follows:

~/.ssh/id_rsa : identification (private) key
~/.ssh/id_rsa.pub : public key

Use scp to copy the id_rsa.pub (public key) to 192.168.0.51 (Server B, Backup) as authorized_keys file, this is know as "installing the public key to server".

scp ~/.ssh/id_rsa.pub root@192.168.0.51:~/.ssh/authorized_keys

You will interact with Server B ssh authentication during this process. Proceed to answer yes and enter the correct password to complete the scp process.

Once completed, test the installed key by ssh'ing into Server B like below:

ssh 192.168.0.51

If you done it correctly, you will now be in Server B shell (No password is requested!). Exit from Server B.

Next, while you are in Server A, test the tar command that send the output to Server B through ssh:

tar zcvf - /var/www/html/projectdir | ssh 192.168.0.51 "cat > /backup/projectdir-$(date +%Y%m%d).tar.gz"

On Server B, checked whether the file is received in /backup directory. If it's there, then you have successfully backup your folder to a remote server over ssh.

Step 2: Add Cron Job for the Backup Process

In order to automate the process, add the tar command above into crontab (on Server A).

First create a backup shell script (save it as ~/backup.sh)

#!/bin/sh
tar zcf - /var/www/html/projectdir | ssh 192.168.0.51 "cat > /backup/projectdir-$(date +%Y%m%d).tar.gz"

After saving the file, give it execution permission with chmod +x ~/backup.sh

Add the script file to crontab like the example below:

0 1 * * * ~/backup.sh

For this example, it will send the backup file everyday at 1:00AM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment