SSH 金鑰認證採用非對稱加密:私鑰留在客戶端,公鑰放置於伺服器 ~/.ssh/authorized_keys。驗證時客戶端以私鑰簽名,伺服器用公鑰驗證,免傳輸密碼,大幅提升安全性。
# 以 root 身份執行
ssh-keygen -t rsa -b 4096
# 建議輸入 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.
# 本機執行
ssh-keygen -t ed25519 -C "your-email@example.com"
# 上傳公鑰到 VPS
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@192.168.0.1
推薦使用 ed25519:金鑰較短、速度較快、安全性優於 RSA 4096。
# 確保 .ssh 目錄權限正確
mkdir -p ~/.ssh
chmod 700 ~/.ssh
# 將公鑰加入 authorized_keys
cat id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# 修正 SELinux 標籤(CentOS/RHEL 必做)
restorecon -Rv ~/.ssh
編輯 /etc/ssh/sshd_config:
# 啟用金鑰認證
PubkeyAuthentication yes
RSAAuthentication yes
# 禁用密碼認證(測試通過後再啟用)
# PasswordAuthentication no
# 禁用 root 密碼登入(建議改為 prohibit-password)
# PermitRootLogin prohibit-password
# 禁用空密碼
PermitEmptyPasswords no
# 限制認證嘗試次數
MaxAuthTries 3
重啟服務生效:
# CentOS 7 / RHEL 7+
systemctl restart sshd
# Ubuntu / Debian
systemctl restart ssh
chmod 600 ~/.ssh/id_rsa
ssh -i ~/.ssh/id_rsa root@192.168.0.1
id_rsa → 儲存為 .ppk → PuTTY Connection → SSH → Auth 選擇私鑰檔# 確認金鑰登入成功後,修改 sshd_config
PasswordAuthentication no
PermitRootLogin prohibit-password # 或 no(需先建立 sudo 使用者)
systemctl restart sshd
| 錯誤訊息 | 原因 | 解決 |
|---|---|---|
| Permission denied (publickey) | 公鑰未正確放入 authorized_keys | 檢查 ~/.ssh/authorized_keys 內容、權限 600、目錄 700 |
| Server refused our key | PuTTY 官方版 PuTTYgen 生成相容性問題 | 使用 WinSCP 附帶 PuTTYgen 重新轉換 |
| Agent admitted failure to sign | ssh-agent 未載入私鑰 | ssh-add ~/.ssh/id_rsa |