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

Linux SSH 免密碼登入完整設定指南:RSA 金鑰對產生、authorized_keys 部署、權限修復與 ssh-copy-id 快速部署

編輯:關於 Linux

透過 SSH 金鑰認證取代密碼登入,不僅提升安全性 (防暴力破解),更能實現自動化部署、腳本遠端執行、Git 操作等無人值守場景。本文詳細說明從金鑰產生、公鑰分發、權限設定到疑難排解的完整流程。

SSH 金鑰認證流程圖

標準部署流程 (手動步驟)

1. 客戶端產生 RSA 金鑰對

ssh-keygen -t rsa -b 4096
# 提示儲存路徑:~/.ssh/id_rsa (私鑰)、~/.ssh/id_rsa.pub (公鑰)
# 建議設定 passphrase 保護私鑰 (可留空為自動化用途)

2. 遠端主機建立 .ssh 目錄

ssh user@remote-host "mkdir -p ~/.ssh"

3. 複製公鑰到遠端 authorized_keys

cat ~/.ssh/id_rsa.pub | ssh user@remote-host 'cat >> ~/.ssh/authorized_keys'

4. 修正遠端權限 (關鍵!)

ssh user@remote-host "chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

一鍵部署神器:ssh-copy-id

# 自動完成步驟 2-4
ssh-copy-id -i ~/.ssh/id_rsa.pub user@remote-host
  • 會提示輸入遠端密碼 (最後一次需要密碼)
  • 自動建立目錄、附加公鑰、設定正確權限

驗證免密登入

ssh user@remote-host
# 應直接進入 Shell,無密碼提示

疑難排解:常見錯誤與修復

錯誤現象原因修復指令
仍提示輸入密碼 authorized_keys 權限過寬 (如 644) chmod 600 ~/.ssh/authorized_keys
日誌顯示 Authentication refused: bad ownership or modes ~/.ssh 目錄權限錯誤 (需 700) chmod 700 ~/.ssh
金鑰類型不支援 遠端 SSH 版本過舊不支援 RSA/ED25519 改用 ssh-keygen -t rsa -b 2048 或升級遠端 OpenSSH
SELinux 環境下拒絕 安全上下文標籤錯誤 restorecon -Rv ~/.ssh
多金鑰衝突 SSH Client 嘗試錯誤金鑰超過 MaxAuthTries 指定金鑰 ssh -i ~/.ssh/id_rsa_custom user@host 或設定 ~/.ssh/config

進階:SSH Config 管理多組金鑰

# ~/.ssh/config
Host github
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github
    IdentitiesOnly yes

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

使用時:ssh github、ssh myserver 自動套用對應金鑰與參數。

安全最佳實踐

  • 私鑰務必設定 Passphrase,搭配 ssh-agent 快取解密狀態
  • 定期輪換金鑰 (建議 90-180 天)
  • 遠端 /etc/ssh/sshd_config 設定 PasswordAuthentication no 強制金鑰認證
  • 使用 ED25519 金鑰 (ssh-keygen -t ed25519) 取得更高安全性與效能
  • 啟用 ssh-keygen -U (OpenSSH 8.2+) 硬體安全金鑰 (FIDO/U2F) 支援

完成設定後,即可享受安全、高效、自動化的 SSH 遠端操作體驗。

Copyright © Windows教程網 All Rights Reserved