SSH(Secure Shell)提供加密遠程登入與數據傳輸,取代 Telnet/FTP 等明文協議。本文針對連接失敗、認證拒絕、金鑰變更三大高頻故障,提供排查步驟與修復指令。
| 模式 | 原理 | 安全性 | 適用場景 |
|---|---|---|---|
| 密碼認證 | 用戶名+密碼加密傳輸 | 防竊聽,但易受暴力破解 | 臨時訪問、內網受信環境 |
| 金鑰認證 | 非對稱加密,私鑰簽名驗證 | 極高,免密碼傳輸,抗中間人攻擊 | 生產環境、自動化腳本、Git 操作 |
ssh: connect to host 172.16.81.221 port 22: No route to host
原因:目標主機未開機、網線未插、網卡 down、防火牆阻斷、路由不可達。
排查:
ping 172.16.81.221 確認三層通telnet 172.16.81.221 22 或 nc -zv 172.16.81.221 22 測試端口systemctl status sshd、iptables -nL、ip linkssh: connect to host 172.16.81.221 port 22: Connection refused
原因:sshd 服務未啟動、監聽地址不匹配(如只聽 127.0.0.1)、TCP Wrapper 拒絕。
修復:
systemctl start sshd
systemctl enable sshd
# 檢查 /etc/ssh/sshd_config
# ListenAddress 0.0.0.0
# PermitRootLogin yes/no 視策略而定
root@172.16.81.221's password:
Permission denied, please try again.
原因:未指定用戶名時預設為 root,但 /etc/ssh/sshd_config 預設 PermitRootLogin prohibit-password 或 no。
修復:
# 編輯配置
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
systemctl reload sshd
最佳實踐:禁止 root 密碼登入,改用普通用戶 + sudo + 金鑰認證。
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Offending key in ~/.ssh/known_hosts:68
RSA host key for 172.16.81.221 has changed...
原因:目標主機重裝系統、更換 IP、重新生成 SSH Host Key、或遭受中間人攻擊。
修復:
# 方法 1:刪除舊指紋(推薦)
ssh-keygen -R 172.16.81.221
# 方法 2:手動編輯
sed -i '68d' ~/.ssh/known_hosts
# 方法 3:完整清理(不推薦)
rm ~/.ssh/known_hosts
再次連接時會提示信任新指紋,輸入 yes 即可。
# ~/.ssh/config
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
TCPKeepAlive yes
Compression yes
ControlMaster auto
ControlPath ~/.ssh/ctrl-%r@%h:%p
ControlPersist 10m
啟用多路複用、保活、壓縮,大幅提升慢鏈路體驗。