步驟 1: 安裝 rsync
如果尚未安裝 rsync,Ubuntu可以通過以下命令安裝:
sudo apt update
sudo apt install rsync
CentOS :
sudo yum install rsync
步驟 2: 編寫備份腳本
下面的腳本在本地服務器上執行,將本地服務器的文件備份到遠程服務器上
#!/bin/bash
# 本地服務器源目錄(會將該目錄的文件備份到遠程服務器)
source_dir="/data/application"
# 遠程服務器地址和目錄
remote_user="root"
remote_host="192.168.127.18"
#將文件備份到遠程服務器下的哪個目錄
remote_backup_dir="/data/backup"
# 獲取當前日期和時間,格式化為 YYYY-MM-DD-HH-MM-SS
timestamp=$(date +"%Y-%m-%d-%H:%M:%S")
# 日誌文件路徑和名稱,根據當前時間命名,每執行一次腳本會生成一個日誌文件
log_file="/data/backup/backup_logs/backup_${timestamp}.log"
# 執行增量備份
rsync -avz --log-file="$log_file" --backup --backup-dir="$remote_backup_dir" "$source_dir" "$remote_user@$remote_host:$remote_backup_dir"
解釋一下這個腳本:
- source_dir: 要備份的源目錄,在本地服務器上
- remote_backup_dir: 你想要存儲備份的目錄。
- rsync -a - --backup --backup-dir=...: 這是 rsync 命令的一般形式:
- -a: 以遞歸模式進行備份,保留文件屬性。
- --backup --backup-dir=...: 將源目錄中被修改或新增的文件備份到遠程服務器
用windows改為,可能會出現:
-bash: ./backup.sh: /bin/bash^M: 壞的解釋器: 沒有那個文件或目錄
用vim/vi打開,執行如下命令:
:set ff=unix
:wq
步驟3:通過ssh公鑰連接遠程服務器
通過下面的命令,查看是否有公鑰和私鑰
ls -l /root/.ssh/id_rsa
ls -l /root/.ssh/id_rsa.pub
下面生成公鑰和私鑰
ssh-keygen -t rsa -f /root/.ssh/id_rsa
將生成的公鑰 ~/.ssh/id_rsa.pub 添加到遠程服務器的 ~/.ssh/authorized_keys 文件中:
#remote_user和remote_server替換成遠程服務器的用户和密碼
ssh-copy-id remote_user@remote_server
步驟 4: 運行備份腳本
確保將腳本設置為可執行,並運行它:
chmod +x backup.sh
./backup.sh
步驟5 通過 Cron 定時備份
1.打開終端並輸入以下命令來編輯當前用户的 cron 任務表:
crontab -e
2.如果是首次編輯 cron 任務表,會提示選擇編輯器(例如 nano 或 vim),選擇一個你喜歡的編輯器進行編輯。
3.在編輯器中添加定時任務,可參考下面的編寫:
#每天凌晨1點執行 backup.sh
0 1 * * * /path/to/backup.sh
#每分鐘執行一次
* * * * * /path/to/backup.sh
#每兩小時執行一次
0 */2 * * * /path/to/backup.sh
4.修改後保存並關閉編輯器。
確保 /path/to/backup.sh 是可執行的腳本文件。如果沒有權限,請先使用 chmod +x /path/to/backup.sh 添加執行權限。
5.手動開啓並開機啓動定時任務:
sudo systemctl enable cron
sudo systemctl start cron