Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

SSH 金鑰認證設定教學:免密碼登入與雙向信任

編輯:Linux 教學

應用場景

  • 伺服器間自動化備份 (scp, rsync)
  • 叢集管理、分散式部署腳本
  • CI/CD 流程自動化部署
  • 提升安全性:停用密碼認證,防止暴力破解

單向信任設定 (A → B)

步驟 1:在伺服器 A 產生金鑰對

[root@A ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):  # Enter 使用預設
Enter passphrase (empty for no passphrase):               # Enter 無密碼
Enter same passphrase again:                              # Enter 確認

Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.

步驟 2:將公鑰複製到伺服器 B

[root@A ~]# scp ~/.ssh/id_rsa.pub root@B:~/.ssh/authorized_keys
# 或使用 ssh-copy-id (較新版本支援)
[root@A ~]# ssh-copy-id root@B

步驟 3:驗證免密碼登入

[root@A ~]# ssh root@B hostname
B

雙向信任設定 (A ↔ B)

在伺服器 B 重複上述步驟 1-3,即可實現雙向免密碼登入。

關鍵檔案權限 (必須正確)

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 600 ~/.ssh/authorized_keys

權限錯誤會導致 SSH 拒絕使用金鑰認證。

進階配置

使用 ssh-agent 管理金鑰

eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa

客戶端配置 ~/.ssh/config

Host myserver
    HostName 192.168.1.100
    User admin
    Port 2222
    IdentityFile ~/.ssh/id_rsa_myserver
    ForwardAgent yes

伺服端強化 /etc/ssh/sshd_config

PubkeyAuthentication yes
PasswordAuthentication no
PermitRootLogin prohibit-password
AuthorizedKeysFile .ssh/authorized_keys

常見問題排查

現象可能原因解決方案
仍提示密碼權限錯誤、authorized_keys 格式錯誤、SELinux 阻擋檢查權限、恢復 SELinux 上下文 restorecon -R ~/.ssh
Connection refusedSSH 服務未啟動、防火牆阻擋、Port 錯誤啟動服務、開放端口
Permission denied (publickey)公鑰未正確部署、用戶名錯誤確認 authorized_keys 內容、指定正確用戶

安全性最佳實務

  1. 生產環境建議使用 ed25519 金鑰 (ssh-keygen -t ed25519)
  2. 重要金鑰設定密碼保護,配合 ssh-agent 使用
  3. 定期輪換金鑰,撤銷舊金鑰
  4. 限制 authorized_keys 來源 IP (from="192.168.1.*" ssh-rsa ...)
  5. 審計日誌監控異常登入

SSH 金鑰認證是 Linux 運維自動化的基石,正確配置能同時提升安全性與操作效率。

Copyright © Windows教程網 All Rights Reserved