萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux SSH 連接常見問題診斷與解決方案

SSH(Secure Shell)提供加密遠程登入與數據傳輸,取代 Telnet/FTP 等明文協議。本文針對連接失敗、認證拒絕、金鑰變更三大高頻故障,提供排查步驟與修復指令。

SSH 兩種認證模式

模式原理安全性適用場景
密碼認證用戶名+密碼加密傳輸防竊聽,但易受暴力破解臨時訪問、內網受信環境
金鑰認證非對稱加密,私鑰簽名驗證極高,免密碼傳輸,抗中間人攻擊生產環境、自動化腳本、Git 操作

故障一:連接端口失敗

現象 1:No route to host

ssh: connect to host 172.16.81.221 port 22: No route to host

原因:目標主機未開機、網線未插、網卡 down、防火牆阻斷、路由不可達。

排查:

  1. ping 172.16.81.221 確認三層通
  2. telnet 172.16.81.221 22 或 nc -zv 172.16.81.221 22 測試端口
  3. 目標機執行 systemctl status sshd、iptables -nL、ip link

現象 2:Connection refused

ssh: 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 視策略而定

故障二:密碼正確但 Permission denied

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!

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 連接優化配置

# ~/.ssh/config
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    TCPKeepAlive yes
    Compression yes
    ControlMaster auto
    ControlPath ~/.ssh/ctrl-%r@%h:%p
    ControlPersist 10m

啟用多路複用、保活、壓縮,大幅提升慢鏈路體驗。

copyright © 萬盛學電腦網 all rights reserved