SSH (Secure Shell) 是 Linux 遠程管理的標準協議,採用客戶端-服務端架構,基於非對稱加密提供安全的遠程登錄、文件傳輸、端口轉發等能力。本文提供 Debian/Ubuntu 系統下 OpenSSH 客戶端與服務端的最小化安裝、配置、登錄驗證與基礎安全加固全流程。
# Debian/Ubuntu
sudo apt update && sudo apt install openssh-client
# RHEL/CentOS/Fedora
sudo dnf install openssh-clients
大多數 Linux 發行版預裝 `openssh-client`,通常無需額外安裝。
# 基本語法
ssh user@host [-p port]
# 範例
ssh 192.168.159.128 # 當前用戶名登錄
ssh -l weiyg 192.168.159.128 # 指定用戶 -l
ssh weiyg@192.168.159.128 # user@host 格式 (推薦)
ssh -p 2222 user@host # 非標準端口
# 1. 生成密鑰對 (本地執行)
ssh-keygen -t ed25519 -C "your@email.com" # 推薦 Ed25519,比 RSA 更快更安全
# 或傳統 RSA
ssh-keygen -t rsa -b 4096 -C "your@email.com"
# 2. 複製公鑰到服務端
ssh-copy-id user@host
# 或手動:cat ~/.ssh/id_ed25519.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
# 3. 驗證免密登錄
ssh user@host
# Debian/Ubuntu
sudo apt update && sudo apt install openssh-server
sudo systemctl enable ssh --now # 設置開機自啟並立即啟動
# RHEL/CentOS/Fedora
sudo dnf install openssh-server
sudo systemctl enable sshd --now
# 服務管理
sudo systemctl status ssh # 查看狀態
sudo systemctl restart ssh # 重啟 (配置修改後必須)
sudo systemctl stop ssh # 停止
# 必須修改的安全項目
Port 2222 # 修改默認端口,減少自動掃描攻擊 (需防火牆同步放行)
PermitRootLogin no # 禁止 root 直接登錄,強制普通用戶 su/sudo
PubkeyAuthentication yes # 啟用公鑰認證
PasswordAuthentication no # 禁用密碼認證 (確認密鑰登錄正常後)
PermitEmptyPasswords no # 禁止空密碼
MaxAuthTries 3 # 最大嘗試次數
ClientAliveInterval 300 # 保活間隔 (秒),防止斷連
ClientAliveCountMax 2 # 最大保活失敗次數
LoginGraceTime 30 # 登錄超時時間
Banner /etc/ssh/banner # 登錄警告橫幅 (法律合規)
AllowUsers admin deploy # 僅允許特定用戶登錄 (白名單)
# DenyUsers * # 或黑名單
# 進階安全
Protocol 2 # 僅支援 SSH-2
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,umac-128-etm@openssh.com
配置生效: `sudo systemctl restart ssh`
# UFW (Ubuntu)
sudo ufw allow 2222/tcp
sudo ufw reload
# firewalld (CentOS/RHEL)
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
# iptables
sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
sudo iptables-save > /etc/iptables/rules.v4
| 現象 | 可能原因 | 排查命令/方案 |
|---|---|---|
| Connection refused | 服務未啟動/端口錯誤/防火牆阻擋 | `systemctl status ssh`、`ss -tlnp \| grep 22`、`ufw status` |
| Permission denied (publickey) | 公鑰未部署/權限錯誤/家目錄權限過寬 | `chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys`、檢查 `sshd_config` `AuthorizedKeysFile` |
| Host key verification failed | 服務端指紋變更 (重裝/中間人攻擊) | `ssh-keygen -R hostname` 移除舊指紋,重新驗證 |
| 閒置斷開 | 無保活機制 | 客戶端 `~/.ssh/config` 加 `ServerAliveInterval 60` 或服務端 `ClientAliveInterval` |
SSH 是 Linux 運維的生命線。花 10 分鐘完成上述配置,能避開 99% 的自動化攻擊與誤操作風險。記住:**安全不是產品,是過程**——定期輪換密鑰、審計日誌、更新 OpenSSH 版本,才能持續守護你的基礎設施。