SSH (Secure Shell) 為加密網路協定,預設埠號 22。常見連線指令:
# 使用當前使用者登入 ssh host # 指定使用者 ssh user@host ssh -p 2222 user@host # 指定非預設埠
The authenticity of host 'host (192.168.0.21)' can't be established. RSA key fingerprint is 98:2e:d7:e0:de:9f:ac:67:28:c2:42:2d:37:16:58:4d. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'host,192.168.0.21' (RSA) to the list of known hosts. user@host's password: ********
輸入 yes 後,主機公鑰會寫入 ~/.ssh/known_hosts,後續連線不再提示。
ssh-keygen -t rsa # 一路 Enter(或自訂路徑/密語) # 產生:~/.ssh/id_rsa(私鑰)、~/.ssh/id_rsa.pub(公鑰)
ssh-copy-id user@host # 若遠端 SSH 埠非 22: ssh-copy-id -p 2222 "user@host"
此命令會將公鑰追加至遠端 ~/.ssh/authorized_keys。
ssh user@host # 應直接進入,無需輸入密碼
檢查遠端 /etc/ssh/sshd_config 確保下列選項開啟:
RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys
修改後重啟 SSH 服務:
# Ubuntu/Debian sudo systemctl restart ssh # 或 sudo service ssh restart # CentOS/RHEL sudo systemctl restart sshd
確保遠端使用者家目錄與 .ssh 權限正確:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
ssh-copy-id -i ~/.ssh/id_rsa.pub user@host # 或手動複製: cat ~/.ssh/id_rsa.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
| 設定項 | 建議值 | 說明 |
|---|---|---|
| Port | 22 (或修改為非標準埠) | 監聽埠 |
| Protocol | 2 | 僅啟用 SSH v2 |
| PermitRootLogin | no | 禁止 root 直接登入 |
| PermitEmptyPasswords | no | 禁止空密碼 |
| LoginGraceTime | 2m | 登入逾時 |
| MaxAuthTries | 6 | 最大嘗試次數 |
| PasswordAuthentication | no (改用金鑰) | 停用密碼認證 |
| PubkeyAuthentication | yes | 啟用金鑰認證 |
| UseDNS | no | 關閉 DNS 反解,加速連線 |
| AllowUsers | user1 user2 | 僅允許特定使用者 |
修改完成後執行 sudo systemctl restart sshd 生效。
# 查看 SSH 服務狀態 systemctl status sshd # 查看 SSH 版本 ssh -V # 測試連線(除錯模式) ssh -vvv user@host # 產生 ED25519 金鑰(更安全、更短) ssh-keygen -t ed25519 -C "comment"
掌握 SSH 金鑰認證與服務端加固,是 Linux 伺服器管理的基本功。建議生產環境**完全停用密碼登入**,改用金鑰加上 fail2ban 或 sshguard 防暴力破解。