ssh user@host
ssh -p 2222 user@host # 指定非預設埠
ssh -i ~/.ssh/id_rsa user@host # 指定私鑰
ssh-keygen -t ed25519 -C "user@host"
# 或傳統 RSA
ssh-keygen -t rsa -b 4096 -C "user@host"
-t ed25519:現代推薦,金鑰短、速度快、安全性高-t rsa -b 4096:相容性最好,舊系統支援~/.ssh/id_ed25519、~/.ssh/id_ed25519.pubssh-copy-id user@host
ssh-copy-id -p 2222 user@host # 非標準埠
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host # 指定公鑰
底層動作:將公鑰內容附加至伺服器 ~/.ssh/authorized_keys。
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_ed25519 # 私鑰僅自己可讀
目錄權限錯誤會導致 SSH 拒絕金鑰認證。
sudo vi /etc/ssh/sshd_config
確保以下選項啟用:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes # 暫時保留密碼登入,確認金鑰可用後再關閉
PermitRootLogin prohibit-password # 僅允許金鑰登入 root
修改後重啟:
sudo systemctl reload sshd
# 或
sudo service ssh reload
| 現象 | 原因與解決 |
|---|---|
| 仍要求密碼 | 檢查伺服器 ~/.ssh 權限、authorized_keys 格式、sshd_config 選項、SELinux 標籤 (restorecon -Rv ~/.ssh) |
| Permission denied (publickey) | 公鑰未正確複製、用戶名錯誤、私鑰不匹配、IdentitiesOnly yes 導致未嘗試正確金鑰 |
| Connection refused | sshd 未啟動、埠號錯誤、防火牆封鎖 |
| Host key verification failed | 伺服器金鑰變更(重裝系統),刪除 ~/.ssh/known_hosts 對應行 |
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519
ssh-add ~/.ssh/id_rsa_github
ssh-add -l # 列出已載入金鑰
設定 ~/.ssh/config 自動選擇金鑰:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
IdentitiesOnly yes
Host myserver
HostName 192.168.1.100
User admin
Port 2222
IdentityFile ~/.ssh/id_ed25519
之後直接 ssh myserver、git push github 即可。
PasswordAuthentication noPermitRootLogin prohibit-passwordfail2ban 防暴力破解AllowUsers user1 user2