Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

SSH RSA 金鑰認證完整配置指南:Linux 與 Windows 雙端免密登入實戰

編輯:Linux 系統常見問題解答

核心原理

非對稱加密:客戶端持有私鑰(id_rsa),伺服器存放公鑰(authorized_keys)。驗證時客戶端用私鑰簽名,伺服器用公鑰驗證,無需傳輸密碼。

伺服器端預檢 /etc/ssh/sshd_config

PubkeyAuthentication yes
RSAAuthentication yes          # SSH-1 相容,新版可省略
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no      # 建議關閉密碼登入(驗證金鑰無誤後)
PermitRootLogin prohibit-password  # 僅允許金鑰登入 root

修改後:systemctl reload sshd

方案一:Linux 客戶端生成金鑰對(標準流程)

1. 生成 RSA 金鑰對

ssh-keygen -t rsa -b 4096 -C "user@host-$(date +%F)"
# -t rsa        加密類型
# -b 4096       金鑰長度(建議 ≥2048,4096 更安全)
# -C            註解,便於辨識

交互提示:

  • Enter file in which to save the key (/home/user/.ssh/id_rsa): → 直接 Enter 使用預設路徑
  • Enter passphrase (empty for no passphrase): → 建議設定強密語保護私鑰,或留空實現全自動化

產出:

  • ~/.ssh/id_rsa:私鑰(權限 600,嚴禁洩露)
  • ~/.ssh/id_rsa.pub:公鑰(可公開分發)

2. 部署公鑰至伺服器

# 方法 A:ssh-copy-id(推薦,自動處理目錄權限)
ssh-copy-id -i ~/.ssh/id_rsa.pub user@server

# 方法 B:手動傳輸
cat ~/.ssh/id_rsa.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

3. 驗證免密登入

ssh user@server  # 應直接進入,無需輸入密碼

方案二:Windows 客戶端使用 PuTTY

1. PuTTYgen 生成金鑰

  1. 執行 puttygen.exe
  2. Parameters → RSA,Bits 4096 → Generate
  3. 滑鼠隨機移動生成熵
  4. Key comment 填寫識別資訊
  5. Key passphrase 設定保護密語(可留空)
  6. Save private key → id_rsa.ppk(PuTTY 專用格式)
  7. 複製視窗上方 Public key for pasting into OpenSSH authorized_keys file 完整內容

2. 伺服器部署公鑰

將複製的公鑰內容追加至 ~/.ssh/authorized_keys(同方案一)。

3. PuTTY 連線配置

  1. Session → Host Name 填 user@server
  2. Connection → SSH → Auth → Private key file for authentication → 選 id_rsa.ppk
  3. 回 Session → Saved Sessions 填名稱 → Save
  4. 雙擊會話即可免密連線

方案三:Linux 伺服器生成金鑰,私鑰分發給 Windows(反向流程)

# 伺服器生成
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_server
mv ~/.ssh/id_rsa_server.pub ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

# 將私鑰 id_rsa_server 下載到 Windows
# PuTTYgen → Conversions → Import Key → 選 id_rsa_server → Save private key → id_rsa_server.ppk
# PuTTY 配置同方案二

權限鐵律(最常見失敗原因)

# 伺服器端
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R user:user ~/.ssh

# 客戶端
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

錯誤提示 Permissions 0755 for '...' are too open 即為權限過寬,嚴格執行上述 chmod 600 即可解決。

進階安全建議

  • 使用 ed25519 替代 RSA:ssh-keygen -t ed25519,更短、更快、更安全
  • 啟用 ssh-agent 管理私鑰解密,避免重複輸入 passphrase
  • 配置 ~/.ssh/config 別名與參數:Host myserver\n HostName 1.2.3.4\n User admin\n IdentityFile ~/.ssh/id_rsa_ed25519
  • 定期輪換金鑰,撤銷舊公鑰
Copyright © Windows教程網 All Rights Reserved