- Server A: Production Server, Example IP: 192.168.0.41
- Server B: Backup Server, Example IP: 192.168.0.51
Backup a folder in Server A and send tarred file to Server B
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.
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.