linux中使用Rsync實現網站自動備份(增量備份)

來源:互聯網
上載者:User


首先,我們假定網站所在的伺服器為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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.