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

CentOS 實現 SSH 免密碼登入:ssh-keygen 產生金鑰對、部署公鑰與權限設定完整流程

編輯:關於 Linux

SSH 免密碼登入(公開金鑰認證)是 Linux 運維自動化的基石。本文以 CentOS 5.3/5.8 為例,說明客戶端產生金鑰對、將公鑰部署至伺服器、設定權限與驗證的標準流程。

SSH 免密碼登入示意圖

環境規劃

角色IP說明
伺服端 (Server)222.73.115.198CentOS 5.3,接受連線
客戶端 (Client)192.168.4.244CentOS 5.8,發起連線

三步驟核心流程

  1. 客戶端產生金鑰對 (ssh-keygen)
  2. 將公鑰複製至伺服器 ~/.ssh/authorized_keys 並設定權限
  3. 測試免密碼登入

詳細操作步驟

1. 客戶端產生 RSA 金鑰對

[root@client ~]# ssh-keygen
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.
The key fingerprint is:
04:45:0b:47:10:92:0c:b2:b9:d7:11:5b:49:05:e4:d9 root@client

2. 檢查生成檔案

[root@client ~]# ls ~/.ssh/
id_rsa  id_rsa.pub  known_hosts
# id_rsa       : 私鑰 (嚴禁外洩,權限 600)
# id_rsa.pub   : 公鑰 (需部署至伺服器)
# known_hosts  : 已知主機金鑰指紋

3. 部署公鑰至伺服器 (兩種方式)

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

[root@client ~]# ssh-copy-id root@222.73.115.198
# 輸入伺服器 root 密碼,自動完成複製與權限設定

方式二:手動複製 (理解原理)

# 客戶端
scp ~/.ssh/id_rsa.pub root@222.73.115.198:/tmp/id_rsa.pub.client

# 伺服器
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cat /tmp/id_rsa.pub.client >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
rm /tmp/id_rsa.pub.client

4. 伺服器 SSH 服務設定確認

# /etc/ssh/sshd_config 關鍵參數
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitRootLogin yes        # 若以 root 登入需開啟
PasswordAuthentication no  # 可選:強制僅允許金鑰登入

# 修改後重啟服務
service sshd restart

5. 驗證免密碼登入

[root@client ~]# ssh root@222.73.115.198
Last login: ...
[root@server ~]#  # 成功進入無需密碼

權限鐵律 (最常見失敗原因)

路徑權限擁有者
~/.ssh700 (drwx------)使用者
~/.ssh/id_rsa600 (-rw-------)使用者
~/.ssh/id_rsa.pub644 (-rw-r--r--)使用者
~/.ssh/authorized_keys600 (-rw-------)使用者

任何權限過寬 (group/other 可讀寫) 會導致 SSH 拒絕使用該金鑰。

進階:非 root 使用者、自訂金鑰名稱、多金鑰管理

  • 一般使用者操作相同,路徑為 ~/.ssh/。
  • 自訂金鑰:ssh-keygen -f ~/.ssh/id_rsa_myserver,連線時 ssh -i ~/.ssh/id_rsa_myserver user@host。
  • ~/.ssh/config 管理多主機:

Host myserver
    HostName 222.73.115.198
    User root
    IdentityFile ~/.ssh/id_rsa_myserver
    Port 22

之後直接 ssh myserver 即可。

安全性最佳實務

  • 生產環境建議使用 ed25519 金鑰:ssh-keygen -t ed25519 (更短、更快、更安全)。
  • 私鑰加密儲存:ssh-keygen -p 修改密語。
  • 定期輪換金鑰,撤銷舊公鑰 (從 authorized_keys 移除)。
  • 啟用 Fail2Ban 防暴力破解,限制 SSH 連線來源 IP。

SSH 免密碼登入是自動化部署、備份同步、叢集管理的前置條件。標準化金鑰管理流程,能大幅提升運維效率與安全性。

Copyright © Windows教程網 All Rights Reserved