SSH 是 Linux 遠程管理的標準協議,加密傳輸、強認證、豐富隧道功能使其成為運維生命線。本文基於 RHEL/CentOS/Fedora 系統,完整覆蓋安裝、雙認證模式配置、安全加固、Windows/Linux 客戶端連線實戰。
# 安裝 OpenSSL 全家桶
yum install -y openssh-server openssh-clients
# 服務管理
systemctl enable --now sshd
systemctl status sshd
systemctl restart sshd # 配置修改後生效
/etc/ssh/sshd_config 精解# 連接埠與監聽
Port 22
# ListenAddress 0.0.0.0 # 指定 IP,預設全監聽
# 安全核心策略
PermitRootLogin no # 禁止 root 直接登入(關鍵)
PasswordAuthentication yes # 啟用密碼認證(模式一)
PermitEmptyPasswords no # 禁止空密碼
LoginGraceTime 1m # 認證等待 1 分鐘
MaxAuthTries 3 # 最大嘗試 3 次
MaxSessions 10 # 最大並發會話
# 金鑰認證(模式二)
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
RSAAuthentication yes # SSH-1 兼容,可省略
# 進階加固
Protocol 2 # 僅支援 SSH-2
X11Forwarding no # 禁用 X11 轉發(非桌面環境)
AllowTcpForwarding no # 禁用 TCP 隧道(按需)
ClientAliveInterval 300 # 5 分鐘無操作發送心跳
ClientAliveCountMax 2 # 2 次無回應斷開
Banner /etc/ssh/banner.txt # 登入法律警告
PasswordAuthentication yes。useradd ops && echo "ComplexPass123!" | passwd --stdin opsssh ops@192.168.1.100# 切換到目標用戶
su - ops
ssh-keygen -t ed25519 -C "ops@$(hostname)-$(date +%F)"
# 推薦 ed25519(比 RSA 2048 更短、更快、更安全)
# 一路 Enter(無密碼短語)或設定強密碼短語(雙因子)
# 查看生成檔案
ls -la ~/.ssh/
# id_ed25519 (私鑰, 600) id_ed25519.pub (公鑰, 644)
# 方法 A:ssh-copy-id(最簡單)
ssh-copy-id -i ~/.ssh/id_ed25519.pub ops@192.168.1.100
# 方法 B:手動部署
scp ~/.ssh/id_ed25519.pub ops@192.168.1.100:/tmp/
ssh ops@192.168.1.100 "
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cat /tmp/id_ed25519.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
rm /tmp/id_ed25519.pub
"
# 編輯 /etc/ssh/sshd_config
PasswordAuthentication no # 關鍵:禁用密碼
PubkeyAuthentication yes
# 重啟生效
systemctl restart sshd
ssh-ed25519 開頭)→ 存為文字檔 → 上傳伺服器 ~/.ssh/authorized_keys(同上)。| 項目 | 配置/操作 | 風險等級 |
|---|---|---|
| 修改預設埠 | Port 2222 + 防火牆放行 + SELinux semanage port -a -t ssh_port_t -p tcp 2222 |
低(避免掃描噪音) |
| Fail2Ban 防暴力破解 | yum install fail2ban → jail.local 設定 maxretry=3 bantime=3600 |
高 |
| 僅允許特定用戶/群組 | AllowUsers ops admin 或 AllowGroups wheel |
高 |
| 禁用 SSH-1 協議 | Protocol 2 |
中 |
| 定期輪換金鑰 | 每 90 天重新生成 ed25519,撤銷舊公鑰 | 高 |
| 審計日誌 | LogLevel VERBOSE → /var/log/secure 分析登入失敗 |
中 |
| 現象 | 排查方向 |
|---|---|
| Permission denied (publickey) | 1. 伺服器 ~/.ssh 700, authorized_keys 6002. 擁有者為用戶本身 3. 公鑰內容完整、無換行斷裂 4. sshd_config PubkeyAuthentication yes |
| Connection refused | 1. systemctl status sshd2. 防火牆 firewall-cmd --add-port=22/tcp3. SELinux getsebool -a | grep ssh |
| Host key verification failed | 已知主機金鑰變更 → ssh-keygen -R hostname 移除舊紀錄 |
SSH 服務搭建核心在於禁用 root 密碼登入、強制 ed25519 金鑰認證、Fail2Ban 動態封鎖。配置即代碼,建議以 Ansible/SaltStack 管理 sshd_config 模板,實現全集群一致性合規。