SSH 金鑰認證 (Public Key Authentication) 是實現伺服器間免密登入、自動化部署、腳本遠端執行的基石。本文詳細說明建立信任關係的標準流程、權限要求、常見陷阱與進階用法。
~/.ssh/authorized_keys 存放對應公鑰 (id_rsa.pub)
ssh-keygen -t rsa -b 4096 -C "user@client-host"
# 一路 Enter (預設路徑 ~/.ssh/id_rsa, 無密碼短語)
# 生產環境建議設定強密碼短語,配合 ssh-agent 使用
ssh-copy-id -i ~/.ssh/id_rsa.pub user2@server-b
# 輸入 user2 密碼一次,自動完成:
# - 建立 ~/.ssh (700)
# - 追加公鑰到 authorized_keys (600)
# - 修正權限
# 客戶端
cat ~/.ssh/id_rsa.pub
# 伺服器 (登入 user2)
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "剛剛複製的公鑰內容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# 確保家目錄權限不超過 755
chmod 755 ~
ssh user2@server-b
# 應直接進入無需密碼
| 路徑 | 權限 | 擁有者 |
|---|---|---|
| ~/.ssh | 700 (drwx------) | user |
| ~/.ssh/id_rsa | 600 (-rw-------) | user |
| ~/.ssh/id_rsa.pub | 644 (-rw-r--r--) | user |
| ~/.ssh/authorized_keys | 600 (-rw-------) | user |
| ~ (家目錄) | ≤755 (drwxr-xr-x) | user |
任何一項不符,SSH 服務端會拒絕金鑰認證回退密碼認證。
/etc/ssh/sshd_config
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 禁用密碼登入 (確認金鑰可用後)
PermitRootLogin prohibit-password # root 僅允許金鑰
ChallengeResponseAuthentication no
UsePAM yes
# 重載生效
systemctl reload sshd
ssh -i /path/to/private_key user@host
~/.ssh/config
Host prod-web
HostName 192.168.1.100
User deploy
Port 2222
IdentityFile ~/.ssh/id_rsa_prod
ForwardAgent yes # 轉發 Agent (跳板機場景)
ServerAliveInterval 60
ServerAliveCountMax 3
之後直接 ssh prod-web 即可。
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa # 輸入一次密碼短語,緩存記憶體
ssh server-b # 後續無需輸入
# 單條命令
ssh user@host "systemctl status nginx"
# 多行腳本 (Here Document)
ssh user@host << 'EOF'
cd /var/www
git pull
systemctl reload php-fpm
EOF
# 複製並執行本地腳本
ssh user@host 'bash -s' < local_script.sh
sftp user@host << 'EOF'
put local_file.txt /remote/path/
get remote_file.log
bye
EOF
sshd_config、authorized_keys 格式 (每行一把鑰、無換行斷裂)、SELinux (restorecon -Rv ~/.ssh)ssh -vvv 除錯,確認嘗試的私鑰、伺服器接受的公鑰類型AllowUsers/DenyUsers 設定ForwardAgent yes、中繼節點 AllowAgentForwarding yesssh-agentLogLevel VERBOSE 記錄金鑰指紋、IP、時間SSH 金鑰信任 = ssh-keygen 產生金鑰對 → ssh-copy-id 部署公鑰 → 嚴格權限 700/600 → sshd_config 禁用密碼。掌握此流程,即可構建安全、自動化、可審計的伺服器運維體系。