如果兩台 Linux 主機都開放 ssh,那麼 scp 是個很值得考虑的備份工具:傳輸走加密通道,安全性高,速度也不差,設定又簡單。唯一的限制是——大檔案不建議用這招,scp 沒有斷點續傳與增量同步能力,幾十 GB 的資料用 rsync 會合適得多。
實驗目標很單純:讓主機 A 在不輸入密碼的情況下,把檔案推送到主機 B。
在 ssh 伺服器端(來源主機)執行:
[root@text ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 按 enter
Enter passphrase (empty for no passphrase): 按 enter
Enter same passphrase again: 按 enter
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx root@text.org
這裡 passphrase 一定要留空,否則每次傳輸都還是會被要求輸入密碼,就失去免密的目的了。
[root@text ~]# cd .ssh/
[root@text .ssh]# ls
id_rsa id_rsa.pub known_hosts
[root@text .ssh]# scp id_rsa.pub root@192.168.0.160:/root/.ssh/authorized_keys
輸入目標主機的密碼,公鑰就傳過去了。之後再傳檔案,就不會再提示輸入密碼。
更省事的做法是直接用 ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.0.160,它會自動處理 authorized_keys 的權限與去重複,不必手動合併。
這一步做完,crontab 的定時備份就有了可靠的基礎。例如:
0 3 * * * /usr/bin/scp /data/backup.tar.gz root@192.168.0.160:/backup/
安全提醒:私鑰千萬不要外傳,權限應為 600;備份帳號若非必要,不建議直接用 root,可建立專用帳號並限制其可寫入的目錄。
作者署名:51cto博客 幼兒園童鞋