如果要做資料備份,那麼異地備份還是一個比較安全有保障的方式,rsync可以輕鬆的搞定這件事情,利用ssh連進遠端電腦,將遠端資料夾備份回本地端。只是每次發動ssh連線都需要輸入密碼,這樣沒辦法利用crontab做定期排程。好在事先做好ssh key的話,就可以省去輸入密碼的步驟。
1.使用SSH key達成免密碼登入遠端電腦
在本地端生成ssh key,通常我會在使用者home資料夾的.ssh目錄裡面做這個事情,這樣所產生的ssh key就會儲存在.ssh目錄裡面
~/.ssh$ ssh-keygen -t rsa
Code language: Bash (bash)
接著會產生兩個key檔,id_rsa及id_rsa.pub
其中副檔名.pub的就是下一步要上傳到遠端的檔案。我們一樣在本地端使用scp指令上傳到遠端去
~/.ssh$ scp id_rsa.pub user_remote@remote_ip:/home/user_remote/.ssh/
Code language: Bash (bash)
接著我們連線到遠端,在遠端電腦將所收到的id_rsa.pub值寫進authorized_keys檔案內
~/.ssh$ cat id_rsa.pub >> .ssh/authorized_keys
Code language: Bash (bash)
最後回到本地端,重新ssh嘗試連進去遠端電腦,這時候應該已經成功不用密碼了
2.使用rsync指令發動異地備份
在本地端嘗試發動rsync看看,應該也不需要密碼了。我這邊加一個–delete指令,這樣遠端如果刪除檔案,本地端的備份也會被刪除,保持一個鏡像關係。
~/$ rsync -avzh --delete user_remote@remote_ip:/遠端要備份的目錄 /本地端的儲存目錄
Code language: Bash (bash)
以上如果沒問題,就可以直接加入crontab了。
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
# backup
20 22 * * * rsync -avzh --delete user_remote@remote_ip:/遠端要備份的目錄 /本地端的儲存目錄
Code language: Bash (bash)