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

Linux SSH 免密碼登入完整設定:金鑰生成、公鑰部署與常見錯誤排除

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

SSH 金鑰認證是最安全、最高效的遠端登入方式。本文從金鑰生成、公鑰分發、權限設定到「Agent admitted failure」錯誤排除,一次講透。

標準設定流程(Client 端操作)

1. 生成金鑰對

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# 或舊版相容:ssh-keygen -t rsa -P ''  # 無密碼金鑰(不建議生產環境)
# 預設產生:~/.ssh/id_rsa (私鑰)、~/.ssh/id_rsa.pub (公鑰)

2. 將公鑰複製到 Server

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

# 方法二:手動複製(舊系統無 ssh-copy-id)
scp ~/.ssh/id_rsa.pub user@192.168.1.100:~/.ssh/
ssh user@192.168.1.100 "mkdir -p ~/.ssh && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && chmod 700 ~/.ssh"

3. 驗證免密登入

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

關鍵權限要求(Server 端)

路徑/檔案權限擁有者
~/.ssh700 (drwx------)user
~/.ssh/authorized_keys600 (-rw-------)user
~/.ssh/id_rsa (Client)600user
~/.ssh/id_rsa.pub644user

權限過寬(如 777、644 私鑰)SSH 守護程式會拒絕使用該金鑰。

常見錯誤與排除

錯誤:Agent admitted failure to sign using the key

原因:SSH Agent 未載入私鑰,或金鑰格式不相容。

解決:

ssh-add ~/.ssh/id_rsa
# 若提示 "Could not open a connection to your authentication agent"
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa

錯誤:Permission denied (publickey)

  1. 檢查 Server /etc/ssh/sshd_config:PubkeyAuthentication yes、AuthorizedKeysFile .ssh/authorized_keys
  2. 確認 authorized_keys 內容正確(單行一把公鑰,無多餘換行)
  3. 檢查目錄/檔案權限(見上表)
  4. 查看 Server 日誌:tail -f /var/log/auth.log 或 journalctl -u sshd -f

SELinux 環境

restorecon -Rv ~/.ssh
# 修正 .ssh 目錄安全性內容標籤

進階:多金鑰管理(~/.ssh/config)


Host github
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github

Host aws-prod
    HostName 10.0.1.50
    User ec2-user
    IdentityFile ~/.ssh/id_rsa_aws
    IdentitiesOnly yes

以 ssh github、ssh aws-prod 自動選擇對應金鑰。

安全建議

  • 私鑰務必加密碼保護(ssh-keygen 會提示輸入 passphrase)
  • 定期輪換金鑰(建議 90-180 天)
  • Server 端停用密碼認證:PasswordAuthentication no(確認金鑰登入正常後)
  • 使用 ssh-agent 快取解密後私鑰,平衡安全與便利

完成設定後,ssh、scp、rsync、git、ansible 等所有 SSH 協定工具皆享免密紅利,是自動化運維的基石。

Copyright © Windows教程網 All Rights Reserved