SSH(Secure Shell)是 Linux 遠端管理的標準協定。本文涵蓋密碼登入、金鑰對認證設定、常見問題排除、sshd_config 關鍵參數調整與安全強化建議。
# 基本登入(預設埠 22)
ssh user@hostname
ssh user@192.168.1.100
# 指定非標準埠
ssh -p 2222 user@host
# 指定身份金鑰
ssh -i ~/.ssh/id_rsa user@host
# 詳細模式(除錯用)
ssh -vvv user@host
首次連線會提示主機金鑰指紋驗證,輸入 yes 信任並寫入 ~/.ssh/known_hosts。
ssh-keygen -t ed25519 -C "user@host-$(date +%F)"
# 或傳統 RSA(較相容):ssh-keygen -t rsa -b 4096
-t ed25519:現代推薦,速度快、金鑰短、安全性高-t rsa -b 4096:相容性最好,舊系統建議~/.ssh/id_ed25519(私鑰)與 ~/.ssh/id_ed25519.pub(公鑰)# 方法一:ssh-copy-id(推薦,自動處理權限)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
# 指定埠
ssh-copy-id -p 2222 -i ~/.ssh/id_ed25519.pub user@host
# 方法二:手動部署
cat ~/.ssh/id_ed25519.pub | ssh user@host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
ssh user@host # 應直接進入,不提示密碼
編輯 /etc/ssh/sshd_config,修改後執行 systemctl reload sshd:
# 協定版本
Protocol 2
# 埠號(建議修改非 22 減少掃描噪音)
Port 2222
# 禁止 root 密碼登入(建議)
PermitRootLogin prohibit-password
# 或完全禁止:PermitRootLogin no
# 禁用密碼認證(僅允許金鑰)
PasswordAuthentication no
PubkeyAuthentication yes
# 限制登入嘗試次數
MaxAuthTries 3
# 登入寬限時間
LoginGraceTime 30s
# 空閒逾時斷線(秒)
ClientAliveInterval 300
ClientAliveCountMax 2
# 禁止空密碼
PermitEmptyPasswords no
# 限制允許登入的使用者/群組
AllowUsers admin deploy
# AllowGroups wheel sshusers
# 禁用 DNS 反向解析(加速登入)
UseDNS no
# 只允許特定介面監聽
ListenAddress 192.168.1.100
# 記錄等級
LogLevel VERBOSE
# 禁止 X11 轉發(無圖形需求時)
X11Forwarding no
# 禁止 TCP 轉發
AllowTcpForwarding no
| 現象 | 原因與解決 |
|---|---|
| 部署公鑰後仍需密碼 | 檢查伺服器 PubkeyAuthentication yes、AuthorizedKeysFile .ssh/authorized_keys、目錄權限 700/檔案 600、SELinux restorecon -Rv ~/.ssh |
| Permission denied (publickey) | 客戶端指定錯誤金鑰 -i、伺服器 authorized_keys 格式錯誤(每行一把)、家目錄權限過寬(需 chmod 700 ~) |
| Connection refused | 埠號錯誤、sshd 未啟動、防火牆攔截、ListenAddress 不匹配 |
| Host key verification failed | 伺服器重裝/金鑰變更,刪除 ~/.ssh/known_hosts 對應行或 ssh-keygen -R hostname |
| Agent admitted failure to sign | 執行 ssh-add 將私鑰加入 agent |
# 啟動 agent 並加入金鑰
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_ed25519
# Agent Forwarding(跳板機場景)
ssh -A user@jump-host
# 在 jump-host 上可直接用本機金鑰連後端伺服器
ssh user@backend-server
# ⚠️ 安全警告:僅信任跳板機時啟用,否則私鑰風險
Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes
Host aws-prod
HostName 10.0.1.50
User ec2-user
IdentityFile ~/.ssh/id_rsa_aws
Port 2222
ProxyJump bastion-host
# 使用簡化指令
ssh github
ssh aws-prod
# 狀態檢查
systemctl status sshd
/etc/init.d/sshd status
# 重新載入配置
systemctl reload sshd
# 重啟服務
systemctl restart sshd
# 查看版本
ssh -V