SSH 金鑰認證比密碼更安全、支援自動化腳本。本文記錄 CentOS 環境下從金鑰生成、公鑰分發、權限鎖定到常見失敗排查的完整標準流程。
| 角色 | IP | 用途 |
|---|---|---|
| Client | 192.168.4.244 | 發起連線 |
| Server | 222.73.115.198 | 接受連線 |
ssh-keygen -t ed25519 -C "user@client-host"
# -t ed25519: 現代橢圓曲線演算法 (比 RSA 4096 更快更安全)
# -C: 註解方便辨識
# 提示輸入檔案路徑 -> Enter 使用預設 ~/.ssh/id_ed25519
# 提示輸入密語 -> Enter 留空 (自動化需無密語) 或設定強密語
產生:
~/.ssh/id_ed25519:私鑰 (嚴格保護,chmod 600)~/.ssh/id_ed25519.pub:公鑰 (可公開分發)方法一:ssh-copy-id (推薦,自動處理權限)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@222.73.115.198
# 輸入密碼一次,自動建立 ~/.ssh、authorized_keys、設定權限
方法二:手動部署
# 1. 複製公鑰內容
cat ~/.ssh/id_ed25519.pub
# 2. Server 端操作
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "公鑰內容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chown -R user:user ~/.ssh
| 路徑 | 權限 | 擁有者 |
|---|---|---|
~/.ssh | 700 (drwx------) | user:user |
~/.ssh/authorized_keys | 600 (-rw-------) | user:user |
~/.ssh/id_ed25519 | 600 | user:user |
~/.ssh/id_ed25519.pub | 644 | user:user |
家目錄 ~ | 755 或 700 | user:user |
任何權限過寬 (group/other 可寫) 將導致 SSH 拒絕金鑰認證回退密碼。
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 禁用密碼登入 (確認金鑰可用後)
PermitRootLogin prohibit-password # root 僅允許金鑰
ChallengeResponseAuthentication no
UsePAM yes
# 重啟生效
systemctl reload sshd
# 正常免密登入
ssh user@222.73.115.198
# 指定私鑰
ssh -i ~/.ssh/id_ed25519 user@222.73.115.198
# 除錯模式 (查看認證流程)
ssh -vvv user@222.73.115.198
# SFTP 測試
sftp -oPort=22 user@222.73.115.198
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keysrestorecon -Rv ~/.ssh (RHEL/CentOS)AuthorizedKeysFile /etc/ssh/keys/%u/authorized_keys-t rsa -b 4096 或啟用 PubkeyAcceptedAlgorithms +ssh-rsanoexec/nosuid 影響腳本執行eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519
# 之後 ssh 連線自動使用 agent 中金鑰,無需輸入密語
標準化 SSH 金鑰部署流程,納入自動化佈署腳本 (Ansible authorized_key 模組),是基礎設施即代碼 核心實踐之一。