首先,我們假定網站所在的伺服器為A伺服器,備份伺服器為B伺服器。安裝rsync的方法就不說了,Linux直接yum/apt-get install rsync就可以了
1.用ssh-key-gen命令在A伺服器上建立公開金鑰和密鑰(目的是免密碼登入B伺服器)
ssh-keygen -t rsa
2.在A伺服器上運行ssh-copy-id命令把公開金鑰複製到B伺服器(.ssh/authorized_key)上
ssh-copy-id -i ~/.ssh/id_rsa.pub root@B伺服器的ip
期間需要輸入B伺服器的密碼
如果出現形如如下錯誤
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
xxxxxxxx
Please contact your system administrator.
Add correct host key in /home/conbar/.ssh/known_hosts to get rid of this message.
Offending key in /home/conbar/.ssh/known_hosts:10
RSA host key for xxxxxx has changed and you have requested strict checking.
Host key verification failed.
在A伺服器下運行如下命令
ssh-keygen -R B伺服器的ip
3.在A伺服器上嘗試登入B伺服器
ssh B伺服器ip
如果成功就沒問題了
4.A伺服器建立備份指令碼(本文樣本是在/root下建立了backup.sh檔案):
樣本1(先打包再同步):
#!/bin/bash
echo "Now packing your database..."
mysqldump -uroot -p資料庫密碼 資料庫名稱> backup.sql
echo "Now your files..."
tar zcvfP backup.tar.gz 網站目錄(如/home/wwwroot)
echo "rsync start..."
echo "Database file is under rsync..."
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/backup.sql B伺服器ip:/home/
echo "Now your files..."
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/backup.tar.gz B伺服器ip:/home/
echo "Complete!"
樣本2(直接同步處理網站目錄,可實現增量備份):
#!/bin/bash
echo "Now packing your database..."
mysqldump -uroot -p資料庫密碼 資料庫名稱> backup.sql
echo "rsync start..."
echo "Database file is under rsync..."
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/backup.sql B伺服器ip:/home/
echo "Now your files..."
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /home/wwwroot B伺服器ip:/home/
echo "Complete!"
5.為備份指令碼增加運行許可權
chmod +x backup.sh
運行sh backup.sh進行備份嘗試
6.設定crontab(crontab -e命令)進行定期備份(每周二、周四淩晨4點開始備份)
# m h dom mon dow command
0 4 * * 1,4 /bin/bash /root/backup.sh