萬盛學電腦網

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

CentOS 實現 SSH 免密碼登入:金鑰對生成、公鑰分發、權限設定與故障排查

SSH 金鑰認證比密碼更安全、支援自動化腳本。本文記錄 CentOS 環境下從金鑰生成、公鑰分發、權限鎖定到常見失敗排查的完整標準流程。

環境規劃

角色IP用途
Client192.168.4.244發起連線
Server222.73.115.198接受連線

Client 端:生成金鑰對

ssh-keygen -t ed25519 -C "user@client-host"
# -t ed25519: 現代橢圓曲線演算法 (比 RSA 4096 更快更安全)
# -C: 註解方便辨識
# 提示輸入檔案路徑 -> Enter 使用預設 ~/.ssh/id_ed25519
# 提示輸入密語 -> Enter 留空 (自動化需無密語) 或設定強密語

產生:

  • ~/.ssh/id_ed25519:私鑰 (嚴格保護,chmod 600)
  • ~/.ssh/id_ed25519.pub:公鑰 (可公開分發)

Server 端:部署公鑰

方法一:ssh-copy-id (推薦,自動處理權限)

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@222.73.115.198
# 輸入密碼一次,自動建立 ~/.ssh、authorized_keys、設定權限

方法二:手動部署

# 1. 複製公鑰內容
cat ~/.ssh/id_ed25519.pub

# 2. Server 端操作
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "公鑰內容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chown -R user:user ~/.ssh

關鍵權限檢查 (最常見失敗原因)

路徑權限擁有者
~/.ssh700 (drwx------)user:user
~/.ssh/authorized_keys600 (-rw-------)user:user
~/.ssh/id_ed25519600user:user
~/.ssh/id_ed25519.pub644user:user
家目錄 ~755 或 700user:user

任何權限過寬 (group/other 可寫) 將導致 SSH 拒絕金鑰認證回退密碼。

Server 端 SSHD 配置優化 (/etc/ssh/sshd_config)

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no          # 禁用密碼登入 (確認金鑰可用後)
PermitRootLogin prohibit-password  # root 僅允許金鑰
ChallengeResponseAuthentication no
UsePAM yes
# 重啟生效
systemctl reload sshd

測試驗證

# 正常免密登入
ssh user@222.73.115.198

# 指定私鑰
ssh -i ~/.ssh/id_ed25519 user@222.73.115.198

# 除錯模式 (查看認證流程)
ssh -vvv user@222.73.115.198

# SFTP 測試
sftp -oPort=22 user@222.73.115.198

SSH 免密登入示意

常見故障排查清單

  1. 權限錯誤:chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys
  2. SELinux 阻擋:restorecon -Rv ~/.ssh (RHEL/CentOS)
  3. 家目錄加密:登入前家目錄未掛載,需 AuthorizedKeysFile /etc/ssh/keys/%u/authorized_keys
  4. 金鑰演算法不支援:舊版 OpenSSH 需 -t rsa -b 4096 或啟用 PubkeyAcceptedAlgorithms +ssh-rsa
  5. 檔案系統掛載選項:noexec/nosuid 影響腳本執行

進階:SSH Agent 管理無密語私鑰

eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519
# 之後 ssh 連線自動使用 agent 中金鑰,無需輸入密語

標準化 SSH 金鑰部署流程,納入自動化佈署腳本 (Ansible authorized_key 模組),是基礎設施即代碼 核心實踐之一。

copyright © 萬盛學電腦網 all rights reserved