scp, rsync)[root@A ~]# ssh-keygen -t rsa
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.
[root@A ~]# scp ~/.ssh/id_rsa.pub root@B:~/.ssh/authorized_keys
# 或使用 ssh-copy-id (較新版本支援)
[root@A ~]# ssh-copy-id root@B
[root@A ~]# ssh root@B hostname
B
在伺服器 B 重複上述步驟 1-3,即可實現雙向免密碼登入。
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 600 ~/.ssh/authorized_keys
權限錯誤會導致 SSH 拒絕使用金鑰認證。
eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa
Host myserver
HostName 192.168.1.100
User admin
Port 2222
IdentityFile ~/.ssh/id_rsa_myserver
ForwardAgent yes
PubkeyAuthentication yes
PasswordAuthentication no
PermitRootLogin prohibit-password
AuthorizedKeysFile .ssh/authorized_keys
| 現象 | 可能原因 | 解決方案 |
|---|---|---|
| 仍提示密碼 | 權限錯誤、authorized_keys 格式錯誤、SELinux 阻擋 | 檢查權限、恢復 SELinux 上下文 restorecon -R ~/.ssh |
| Connection refused | SSH 服務未啟動、防火牆阻擋、Port 錯誤 | 啟動服務、開放端口 |
| Permission denied (publickey) | 公鑰未正確部署、用戶名錯誤 | 確認 authorized_keys 內容、指定正確用戶 |
ed25519 金鑰 (ssh-keygen -t ed25519)ssh-agent 使用authorized_keys 來源 IP (from="192.168.1.*" ssh-rsa ...)SSH 金鑰認證是 Linux 運維自動化的基石,正確配置能同時提升安全性與操作效率。