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 免密登入 (金鑰信任) 完整配置指南

編輯:Linux 教學

SSH 金鑰認證 (Public Key Authentication) 是實現伺服器間免密登入、自動化部署、腳本遠端執行的基石。本文詳細說明建立信任關係的標準流程、權限要求、常見陷阱與進階用法。

核心原理

  • 客戶端持有私鑰 (id_rsa,權限 600,絕不外洩)
  • 伺服器 ~/.ssh/authorized_keys 存放對應公鑰 (id_rsa.pub)
  • 連線時客戶端用私鑰簽名挑戰,伺服器用公鑰驗證,無需傳輸密碼

標準建立流程 (Client A → Server B)

1. 客戶端產生金鑰對 (若已存在可跳過)


ssh-keygen -t rsa -b 4096 -C "user@client-host"
# 一路 Enter (預設路徑 ~/.ssh/id_rsa, 無密碼短語)
# 生產環境建議設定強密碼短語,配合 ssh-agent 使用

2. 複製公鑰到伺服器 (推薦 ssh-copy-id)


ssh-copy-id -i ~/.ssh/id_rsa.pub user2@server-b
# 輸入 user2 密碼一次,自動完成:
# - 建立 ~/.ssh (700)
# - 追加公鑰到 authorized_keys (600)
# - 修正權限

3. 手動複製 (無 ssh-copy-id 時)


# 客戶端
cat ~/.ssh/id_rsa.pub

# 伺服器 (登入 user2)
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "剛剛複製的公鑰內容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# 確保家目錄權限不超過 755
chmod 755 ~

4. 驗證免密登入


ssh user2@server-b
# 應直接進入無需密碼

關鍵權限鐵律 (權限錯誤 = 認證失敗)

路徑權限擁有者
~/.ssh700 (drwx------)user
~/.ssh/id_rsa600 (-rw-------)user
~/.ssh/id_rsa.pub644 (-rw-r--r--)user
~/.ssh/authorized_keys600 (-rw-------)user
~ (家目錄)≤755 (drwxr-xr-x)user

任何一項不符,SSH 服務端會拒絕金鑰認證回退密碼認證。

伺服器端 SSHD 配置強化 /etc/ssh/sshd_config


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

進階用法

1. 指定私鑰檔案連線


ssh -i /path/to/private_key user@host

2. SSH Config 簡化連線 ~/.ssh/config


Host prod-web
    HostName 192.168.1.100
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_rsa_prod
    ForwardAgent yes   # 轉發 Agent (跳板機場景)
    ServerAliveInterval 60
    ServerAliveCountMax 3

之後直接 ssh prod-web 即可。

3. ssh-agent 管理帶密碼短語的私鑰


eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa  # 輸入一次密碼短語,緩存記憶體
ssh server-b  # 後續無需輸入

4. 遠端執行命令/腳本 (自動化核心)


# 單條命令
ssh user@host "systemctl status nginx"

# 多行腳本 (Here Document)
ssh user@host << 'EOF'
cd /var/www
git pull
systemctl reload php-fpm
EOF

# 複製並執行本地腳本
ssh user@host 'bash -s' < local_script.sh

5. SFTP 免密傳檔


sftp user@host << 'EOF'
put local_file.txt /remote/path/
get remote_file.log
bye
EOF

常見問題排查

  • 仍提示密碼:檢查權限、sshd_config、authorized_keys 格式 (每行一把鑰、無換行斷裂)、SELinux (restorecon -Rv ~/.ssh)
  • Permission denied (publickey):ssh -vvv 除錯,確認嘗試的私鑰、伺服器接受的公鑰類型
  • 連線逾時:防火牆、Security Group、IP 限制、AllowUsers/DenyUsers 設定
  • Agent forwarding 失效:確認兩端 ForwardAgent yes、中繼節點 AllowAgentForwarding yes

安全最佳實踐

  1. 私鑰加密儲存 (設定密碼短語) + ssh-agent
  2. 定期輪換金鑰 (每 90-180 天)
  3. 最小權限:部署帳號僅擁有必要目錄權限,禁用 root 直接登入
  4. 審計日誌:LogLevel VERBOSE 記錄金鑰指紋、IP、時間
  5. 硬體金鑰:高敏感環境使用 YubiKey/FIDO2 (ssh-keygen -t ecdsa-sk)

總結

SSH 金鑰信任 = ssh-keygen 產生金鑰對 → ssh-copy-id 部署公鑰 → 嚴格權限 700/600 → sshd_config 禁用密碼。掌握此流程,即可構建安全、自動化、可審計的伺服器運維體系。

Copyright © Windows教程網 All Rights Reserved