環境假設
- 本地端 (Client):10.1.1.1,用戶
user
- 遠端端 (Server):10.1.1.2,用戶
root
步驟 1:本地端產生金鑰對
ssh-keygen -t rsa
# 一路 Enter (無密碼短語)
# 產生 ~/.ssh/id_rsa (私鑰) 與 ~/.ssh/id_rsa.pub (公鑰)
步驟 2:部署公鑰至遠端
# 方法 A:ssh-copy-id (推薦,自動建立目錄與權限)
ssh-copy-id root@10.1.1.2
# 方法 B:手動
scp ~/.ssh/id_rsa.pub root@10.1.1.2:/tmp/
ssh root@10.1.1.2 "mkdir -p ~/.ssh && cat /tmp/id_rsa.pub >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
步驟 3:驗證免密碼登入
ssh root@10.1.1.2 # 應直接進入 Shell
scp file.txt root@10.1.1.2:/path/ # 直接複製無需輸入密碼
SCP 常用語法速查
| 操作 | 指令 |
| 本地 → 遠端 (檔案) | scp file user@host:/remote/path |
| 遠端 → 本地 (檔案) | scp user@host:/remote/file /local/path |
| 本地 → 遠端 (目錄) | scp -r dir user@host:/remote/path |
| 遠端 → 本地 (目錄) | scp -r user@host:/remote/dir /local/path |
進階:SSH Agent 避免重複輸入密碼短語
eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa # 若金鑰有設定 passphrase,只需輸入一次
注意事項
~/.ssh 權限必須 700,authorized_keys 必須 600,否則 sshd 會拒絕使用。
- 若遠端
/etc/ssh/sshd_config 設定 PermitRootLogin prohibit-password,Root 僅能用金鑰登入,更安全。