萬盛學電腦網

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

SSH 金鑰對免密碼登入設定教學:原理、步驟與最佳實務

SSH 金鑰認證採用非對稱加密:客戶端持有私鑰,伺服器存放對應公鑰。連線時客戶端以私鑰簽名挑戰,伺服器用公鑰驗證,通過即登入,無需輸入密碼,安全性遠高於密碼認證。

核心檔案位置

  • 客戶端私鑰:~/.ssh/id_rsa(或 id_ed25519)
  • 客戶端公鑰:~/.ssh/id_rsa.pub
  • 伺服器授權公鑰庫:~/.ssh/authorized_keys(每行一個公鑰)

標準建立流程

# 1. 客戶端產生金鑰對(推薦 Ed25519,更安全、金鑰更短)
ssh-keygen -t ed25519 -C "user@host-$(date +%F)"
# 或傳統 RSA 4096 bits
ssh-keygen -t rsa -b 4096 -C "user@host-$(date +%F)"

# 提示輸入檔案路徑(直接 Enter 使用預設)、密碼短語(建議設定,空則免輸入)

# 2. 將公鑰複製到伺服器(需一次密碼登入)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server_ip
# 或手動
cat ~/.ssh/id_ed25519.pub | ssh user@server_ip "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

# 3. 驗證免密登入
ssh user@server_ip

伺服器端安全加固(/etc/ssh/sshd_config)

PubkeyAuthentication yes
PasswordAuthentication no          # 禁用密碼登入(確認金鑰登入正常後)
PermitRootLogin prohibit-password  # root 僅允許金鑰登入
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
ClientAliveInterval 60
ClientAliveCountMax 3

修改後:systemctl reload sshd

多主機管理技巧

SSH Config 別名(~/.ssh/config)

Host prod-web
    HostName 192.168.10.10
    User admin
    IdentityFile ~/.ssh/id_ed25519_prod
    Port 2222

Host gitlab
    HostName git.example.com
    User git
    IdentityFile ~/.ssh/id_ed25519_gitlab

之後直接 ssh prod-web 即可連線。

多台伺服器分發公鑰

for host in web1 web2 db1 db2; do
  ssh-copy-id -i ~/.ssh/id_ed25519.pub $host
done

進階:SSH Agent 避免重複輸入密碼短語

eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519   # 輸入一次密碼短語,session 期間自動應答
# 加入 ~/.bashrc 自動啟動

常見問題排查

最佳實務清單

  • ✅ 採用 Ed25519 金鑰(或 RSA ≥ 4096 bits)。
  • ✅ 私鑰設定強密碼短語,配合 ssh-agent 使用。
  • ✅ 伺服器強制 PasswordAuthentication no。
  • ✅ 定期輪換金鑰(建議每年),撤銷舊公鑰。
  • ✅ 重要伺服器啟用 FIDO2/U2F 硬體金鑰(sk-ssh-ed25519@openssh.com)。
  • ✅ 審計 /var/log/secure / /var/log/auth.log 登入紀錄。

SSH 金鑰認證是 Linux 伺服器存取安全的基石,正確部署並持續管理,能有效阻擋暴力破解與憑證竊取攻擊。

copyright © 萬盛學電腦網 all rights reserved
現象原因解決
Permission denied (publickey)公鑰未加入 authorized_keys、權限錯誤、SELinux 標籤錯誤chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; restorecon -Rv ~/.ssh
金鑰被拒絕伺服器 sshd_config 禁用 PubkeyAuthentication檢查設定並 reload sshd
連線逾時防火牆阻擋、Port 錯誤、IP 封鎖檢查 security group、firewalld、iptables、fail2ban