非對稱加密:客戶端持有私鑰 (id_rsa),服務端存儲對應公鑰 (authorized_keys)。認證時客戶端證明擁有私鑰,無需傳輸密碼。
ssh-keygen -t rsa -b 4096 -C "user@host-$(date +%F)"
# -t rsa: 加密算法 (推薦 rsa 4096 或 ed25519)
# -b 4096: 密鑰長度
# -C: 註釋 (便於識別)
# 交互提示:
# Enter file in which to save the key (/home/user/.ssh/id_rsa): [回車接受默認]
# Enter passphrase (empty for no passphrase): [可輸入密語保護私鑰,或留空自動化]
# Enter same passphrase again: [確認]
生成文件:
~/.ssh/id_rsa:私鑰 (權限 600,**極其機密**)~/.ssh/id_rsa.pub:公鑰 (可公開分發)
ssh-copy-id -i ~/.ssh/id_rsa.pub user@remote_host
# 輸入一次密碼,自動追加公鑰至遠程 ~/.ssh/authorized_keys
# 1. 確保遠程 .ssh 目錄存在且權限正確
ssh user@remote_host "mkdir -p ~/.ssh && chmod 700 ~/.ssh"
# 2. 追加公鑰
cat ~/.ssh/id_rsa.pub | ssh user@remote_host "cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
ssh user@remote_host
# 應直接進入 Shell,無需輸入密碼
# 測試 SCP
scp /local/file user@remote_host:/remote/path
| 路徑 | 權限 | 擁有者 | 說明 |
|---|---|---|---|
| ~/.ssh | 700 (drwx------) | user:user | 僅擁有者可進入 |
| ~/.ssh/authorized_keys | 600 (-rw-------) | user:user | 僅擁有者可讀寫 |
| ~/.ssh/id_rsa (客戶端) | 600 | user:user | 私鑰絕對不可被其他用戶讀取 |