萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux SSH 遠端登入與免密碼金鑰認證完整設定教學

一、基本 SSH 登入

ssh user@host
ssh -p 2222 user@host          # 指定非預設埠
ssh -i ~/.ssh/id_rsa user@host # 指定私鑰

二、建立免密碼登入(公開金鑰認證)

1. 客戶端產生金鑰對

ssh-keygen -t ed25519 -C "user@host"
# 或傳統 RSA
ssh-keygen -t rsa -b 4096 -C "user@host"
  • -t ed25519:現代推薦,金鑰短、速度快、安全性高
  • -t rsa -b 4096:相容性最好,舊系統支援
  • 一路 Enter 使用預設路徑 ~/.ssh/id_ed25519、~/.ssh/id_ed25519.pub
  • 可選擇設定 passphrase 保護私鑰(建議設定)

2. 將公鑰複製到伺服器

ssh-copy-id user@host
ssh-copy-id -p 2222 user@host              # 非標準埠
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host  # 指定公鑰

底層動作:將公鑰內容附加至伺服器 ~/.ssh/authorized_keys。

3. 伺服器端權限確認(關鍵)

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_ed25519   # 私鑰僅自己可讀

目錄權限錯誤會導致 SSH 拒絕金鑰認證。

4. sshd 設定檔確認

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 refusedsshd 未啟動、埠號錯誤、防火牆封鎖
Host key verification failed伺服器金鑰變更(重裝系統),刪除 ~/.ssh/known_hosts 對應行

四、進階:SSH Agent 管理多把金鑰

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 即可。

五、安全性強化建議

  1. 停用密碼認證:PasswordAuthentication no
  2. 停用 Root 密碼登入:PermitRootLogin prohibit-password
  3. 變更預設埠(非 22)減少掃描噪音
  4. 使用 fail2ban 防暴力破解
  5. 限制允許登入使用者:AllowUsers user1 user2
  6. 啟用雙因子驗證(Google Authenticator / TOTP)
copyright © 萬盛學電腦網 all rights reserved