Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 腳本實現遠端自動備份:SSH 金鑰免密登入 + rsync/scp 定時同步完整教學

編輯:系統常見問題解答

本機備份無法防禦硬碟實體損壞,遠端手動備份耗時不及時。最佳方案:**SSH 金鑰免密登入 + rsync/scp 腳本 + crontab 定時執行**。

步驟 1:建立 SSH 金鑰對 (A 機 → B 機免密登入)


# A 機執行
ssh-keygen -t rsa
# 三次 Enter (無密碼短語)
# 產生 /root/.ssh/id_rsa (私鑰) 與 id_rsa.pub (公鑰)

步驟 2:部署公鑰至 B 機


# A 機傳送公鑰
scp /root/.ssh/id_rsa.pub root@B_IP:/tmp

# B 機登入部署
cd ~/.ssh
cat /tmp/id_rsa.pub >> authorized_keys
chmod 400 authorized_keys
rm -f /tmp/id_rsa.pub

步驟 3:驗證免密登入


# A 機測試
ssh root@B_IP  # 應直接進入無需密碼

關鍵:authorized_keys 權限**必須 400**,777 會導致拒絕金鑰認證回退密碼驗證。

步驟 4:撰寫備份腳本 + crontab 定時


#!/bin/bash
# backup.sh
rsync -avz --delete /source/data/ root@B_IP:/backup/data/
# 或 scp -r /source/data root@B_IP:/backup/

# crontab -e
0 2 * * * /root/scripts/backup.sh >> /var/log/backup.log 2>&1  # 每天凌晨 2 點執行
測試環境:Red Hat 9.0 驗證通過。現代發行版 (CentOS/RHEL/Ubuntu/Debian) 同樣適用。生產環境建議:加入錯誤通知 (mail/Telegram)、備份保留策略、加密傳輸 (rsync over SSH 預設加密)、異地多點備份。
Copyright © Windows教程網 All Rights Reserved