Linux 主機之間搬檔案,最順手的工具就是 scp。它走 ssh 通道,預設每次都要輸入對方密碼,批次作業時特別礙事。解法是事先建立金鑰信任關係,之後就能無痛傳輸。
以下用兩台主機示範:A 的 IP 是 192.168.10.1,B 的 IP 是 192.168.10.2,目標是從 A 免密碼複製檔案到 B。
ssh-keygen -t rsa
過程中會問存檔位置與 passphrase,這裡的關鍵是 passphrase 一定要留空直接按 Enter,否則免密碼就白做了。
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
將 id_rsa.pub 複製到 B 的 ~/.ssh/ 目錄,並改名為 authorized_keys:
scp .ssh/id_rsa.pub 192.168.10.2:/root/.ssh/authorized_keys
完成後,從 A 用 scp 推到 B 就不再需要密碼。
兩台機器的帳號名稱必須一致(本例都用 root)。基於安全考量,比較妥當的做法是在兩台機器各建立一個專用帳號,在 A 上以 su 切換過去執行步驟一。
另外,B 上的 .ssh 目錄可能根本還不存在,需要手動建立。若 B 已經有 authorized_keys,別急著覆蓋——這個檔案可以容納多組公鑰,用附加的方式寫入即可:
scp .ssh/id_rsa.pub 192.168.10.2:/root/.ssh/a.pub
cat ~/.ssh/a.pub >> ~/.ssh/authorized_keys