萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux VPS 啟用 SSH 金鑰認證完整教學:從金鑰生成到禁用密碼登入

SSH 金鑰認證架構概覽

SSH 金鑰認證採用非對稱加密:私鑰留在客戶端,公鑰放置於伺服器 ~/.ssh/authorized_keys。驗證時客戶端以私鑰簽名,伺服器用公鑰驗證,免傳輸密碼,大幅提升安全性。

步驟 1:生成金鑰對

方法一:在 VPS 上生成(最簡單)

# 以 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。

步驟 2:伺服器端部署公鑰

# 確保 .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

步驟 3:修改 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

步驟 4:客戶端連線測試

Linux/macOS 客戶端

chmod 600 ~/.ssh/id_rsa
ssh -i ~/.ssh/id_rsa root@192.168.0.1

Windows 客戶端

  • PuTTY:使用 WinSCP 附帶的 PuTTYgen 載入 id_rsa → 儲存為 .ppk → PuTTY Connection → SSH → Auth 選擇私鑰檔
  • Xshell:工具 → 使用者金鑰管理 → 導入私鑰 → 會話屬性 → 使用者認證選擇 Public Key
  • Windows 10+ OpenSSH:同 Linux 用法

步驟 5:驗證無誤後強化安全

# 確認金鑰登入成功後,修改 sshd_config
PasswordAuthentication no
PermitRootLogin prohibit-password  # 或 no(需先建立 sudo 使用者)

systemctl restart sshd

常見問題排查

最佳實踐總結

  1. 優先使用 ed25519 金鑰
  2. 私鑰務必設定 passphrase
  3. 使用 ssh-agent 避免重複輸入 passphrase
  4. 定期輪換金鑰(建議每年)
  5. 重要伺服器部署 Fail2ban + Port Knocking 多層防護
copyright © 萬盛學電腦網 all rights reserved
錯誤訊息原因解決
Permission denied (publickey)公鑰未正確放入 authorized_keys檢查 ~/.ssh/authorized_keys 內容、權限 600、目錄 700
Server refused our keyPuTTY 官方版 PuTTYgen 生成相容性問題使用 WinSCP 附帶 PuTTYgen 重新轉換
Agent admitted failure to signssh-agent 未載入私鑰ssh-add ~/.ssh/id_rsa