SSH 金鑰認證採用非對稱加密:客戶端持有私鑰,伺服器存放對應公鑰。連線時客戶端以私鑰簽名挑戰,伺服器用公鑰驗證,通過即登入,無需輸入密碼,安全性遠高於密碼認證。
~/.ssh/id_rsa(或 id_ed25519)~/.ssh/id_rsa.pub~/.ssh/authorized_keys(每行一個公鑰)# 1. 客戶端產生金鑰對(推薦 Ed25519,更安全、金鑰更短)
ssh-keygen -t ed25519 -C "user@host-$(date +%F)"
# 或傳統 RSA 4096 bits
ssh-keygen -t rsa -b 4096 -C "user@host-$(date +%F)"
# 提示輸入檔案路徑(直接 Enter 使用預設)、密碼短語(建議設定,空則免輸入)
# 2. 將公鑰複製到伺服器(需一次密碼登入)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server_ip
# 或手動
cat ~/.ssh/id_ed25519.pub | ssh user@server_ip "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
# 3. 驗證免密登入
ssh user@server_ip
PubkeyAuthentication yes
PasswordAuthentication no # 禁用密碼登入(確認金鑰登入正常後)
PermitRootLogin prohibit-password # root 僅允許金鑰登入
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
ClientAliveInterval 60
ClientAliveCountMax 3
修改後:systemctl reload sshd
Host prod-web
HostName 192.168.10.10
User admin
IdentityFile ~/.ssh/id_ed25519_prod
Port 2222
Host gitlab
HostName git.example.com
User git
IdentityFile ~/.ssh/id_ed25519_gitlab
之後直接 ssh prod-web 即可連線。
for host in web1 web2 db1 db2; do
ssh-copy-id -i ~/.ssh/id_ed25519.pub $host
done
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519 # 輸入一次密碼短語,session 期間自動應答
# 加入 ~/.bashrc 自動啟動
| 現象 | 原因 | 解決 |
|---|---|---|
| Permission denied (publickey) | 公鑰未加入 authorized_keys、權限錯誤、SELinux 標籤錯誤 | chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; restorecon -Rv ~/.ssh |
| 金鑰被拒絕 | 伺服器 sshd_config 禁用 PubkeyAuthentication | 檢查設定並 reload sshd |
| 連線逾時 | 防火牆阻擋、Port 錯誤、IP 封鎖 | 檢查 security group、firewalld、iptables、fail2ban |