Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

SSH 服務無法登入?系統化排查六步法:從網路到服務進程

編輯:關於伺服器

教學情境:真實課堂案例複盤

學員反映「SSH 突然連不上」,紛紛猜測:「網卡壞了?」、「網路線鬆了?」、「客戶端問題?」。講師強調:排除法需有邏輯順序,不可隨意猜測。以下為標準排查流程 (SOP)。

六步系統化排查法

Step 1:確認故障前狀態與同網段連通性

  • 故障前 SSH 是否正常?
  • 同網段其他伺服器 SSH 是否可連?
  • 是 → 排除網路基礎設施 (交換器/防火牆/路由/ISP) 問題,鎖定單機
    否 → 檢查網路設備、VLAN、ACL、防火牆規則、聯繫網管/ISP

Step 2:本機回環測試 (排除網卡/驅動/協議棧)

ping 127.0.0.1
ping ::1 (IPv6)
  • 失敗 → 作業系統網路協議棧損壞、網卡驅動異常、防火牆封鎖本機回環
  • 成功 → 網卡硬體/驅動/TCP/IP 棧基本正常

Step 3:檢查設定檔異動與操作審計

  • 查看 /var/log/secure、/var/log/auth.log、/var/log/messages 近期錯誤
  • history 或 last -n 20 確認是否有人修改 /etc/ssh/sshd_config、iptables/firewalld、SELinux 政策
  • 常見誤改:Port 22 改為非常用埠卻未同步防火牆/客戶端、PermitRootLogin no、PasswordAuthentication no 未設金鑰、AllowUsers/DenyUsers 誤鎖帳號

Step 4:驗證 SSH 服務進程與監聽埠

# 檢查進程
ps -ef | grep sshd
# 應見到:/usr/sbin/sshd -D (主進程) + 可能的 privilege separation 子進程

# 檢查監聽埠
netstat -anp | grep sshd
ss -anp | grep sshd
# 應見到:LISTEN 0.0.0.0:22 或 :: :22、PID/程式名稱 sshd
  • 無進程/無監聽埠 → 服務未啟動或啟動失敗
  • 監聽非 22 埠 → 確認客戶端指定 -p PORT

Step 5:重啟 SSH 服務 (最常見修復)

systemctl restart sshd
# 或
service sshd restart
# SysVinit
/etc/init.d/sshd restart
  • 啟動成功 → 觀察日誌確認監聽埠、金鑰生成無誤
  • 啟動失敗 → 進入 Step 6

Step 6:依據錯誤訊息與日誌深度診斷

journalctl -u sshd -n 50 --no-pager
# 或
cat /var/log/messages | grep sshd

進階防護與自動化

  • Fail2Ban / sshguard:自動封鎖暴力破解 IP
  • Port Knocking / SPA:隱藏 SSH 埠,需特定序列敲門才開放
  • 金鑰登入強制:PasswordAuthentication no、PubkeyAuthentication yes、禁用 Root 登入
  • 雙因子認證 (2FA):Google Authenticator PAM 模組 / Duo / YubiKey
  • 監控告警:Prometheus node_exporter + sshd_exporter 監控連線數、失敗率、暴力破解嘗試

一頁式速查卡 (建議貼機房機櫃)


SSH 連不上?依序執行:
1. ping 同網段主機 → 排除網路
2. ping 127.0.0.1 → 排除本機協議棧
3. history / log → 排除人為誤改
4. ps -ef | grep sshd ; ss -anp | grep :22 → 確認進程/埠
5. systemctl restart sshd → 嘗試修復
6. journalctl -u sshd → 深度診斷
Copyright © Windows教程網 All Rights Reserved
常見錯誤成因修復
Bind to port 22 failed: Address already in use殘留進程、其他服務佔用 22 埠kill -9 PID / 修改 sshd_config Port
Missing privilege separation directory/var/run/sshd 或 /var/empty/sshd 缺失mkdir -p /var/run/sshd; restorecon -R /var/run/sshd
Bad configuration option: xxxsshd_config 語法錯誤/不支援選項sshd -t 測試配置、修正或刪除錯誤行
Permission denied (publickey,password)金鑰權限/擁有者錯誤、SELinux 標籤錯誤chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; restorecon -R ~/.ssh
fatal: Cannot bind any addressListenAddress 設定錯誤、IPv6 未啟用但設定 ::修正 ListenAddress 或啟用 IPv6