萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux SSH 免密登入配置指南:雙向金鑰信任建立與故障排查

SSH 金鑰認證是 Linux 伺服器互信、自動化部署、叢集管理的基石。本文詳細記錄雙向免密登入配置流程與常見故障排查。

環境假設

  • 兩台伺服器:GZFS2A、GZFS2B
  • 均以 root 執行(生產環境**強烈建議使用專用服務帳號**,禁用 root 登入)

標準配置流程(現代最佳實踐)

1. 於雙方生成 Ed25519 金鑰對(比 DSA/RSA 更安全高效)

# 在 GZFS2A
ssh-keygen -t ed25519 -C "gzfs2a-root"
# 在 GZFS2B
ssh-keygen -t ed25519 -C "gzfs2b-root"
# 一路 Enter 採用預設路徑 ~/.ssh/id_ed25519、無密碼金鑰(或設定強密碼配合 ssh-agent)

2. 交換公鑰至對方 authorized_keys

# GZFS2A → GZFS2B
ssh-copy-id root@GZFS2B
# 或手動:
cat ~/.ssh/id_ed25519.pub | ssh root@GZFS2B "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

# GZFS2B → GZFS2A
ssh-copy-id root@GZFS2A

3. 驗證雙向免密

ssh GZFS2B hostname
ssh GZFS2A hostname

無需輸入密碼即成功。

原文舊版 DSA 流程(僅供參考)

ssh-keygen -t dsa
cat id_dsa.GZFS2B >> authorized_keys2
scp root@GZFS2B:/root/.ssh/id_dsa.pub /root/.ssh/id_dsa.GZFS2B
cat id_dsa.GZFS2B >> authorized_keys2

已棄用:DSA 限制 1024 位元,OpenSSH 7.0+ 預設停用,請改用 Ed25519 或 RSA 4096。

關鍵權限要求(權限錯誤導致拒絕金鑰)

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

sshd_config 關鍵設定

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no          # 禁用密碼登入(建議)
PermitRootLogin prohibit-password  # 僅允許金鑰登入 root
ChallengeResponseAuthentication no
UsePAM yes

修改後 systemctl reload sshd。

故障排查清單

  1. ssh -vvv target 觀察 debug 輸出:Offering public key、Server accepts key、Authentication succeeded
  2. 檢查 /var/log/auth.log / /var/log/secure 錯誤訊息
  3. 確認 SELinux/AppArmor:restorecon -Rv ~/.ssh
  4. 家目錄權限:chmod 755 /home/user(不得群組/他人可寫)
  5. 若仍失敗:rm -rf ~/.ssh && ssh-keygen ... && ssh-copy-id ... 重建

進階:ssh-agent 避免重複輸入金鑰密碼

eval $(ssh-agent)
ssh-add ~/.ssh/id_ed25519
# 之後 ssh 連線無需輸入金鑰密碼

配合 ForwardAgent yes 實現跳板機透傳認證。

copyright © 萬盛學電腦網 all rights reserved
路徑權限擁有者
~/.ssh700user:user
~/.ssh/authorized_keys600user:user
~/.ssh/id_ed25519600user:user
~/.ssh/id_ed25519.pub644user:user