解決使用SSH連線Linux伺服器時連線失敗的故障

小宇飛刀發表於2018-08-12

最近使用Xshell連線Linux伺服器,報錯:Connection closed by foreign host. Disconnected from remote host,詳細報錯資訊是:

[C:\~]$ ssh root@210.35.124.82


Connecting to 210.35.124.2:22...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(210.35.124.82:22) at 08:34:46.

Type `help' to learn how to use Xshell prompt.

通過控制檯從本地登入伺服器,使用last指令檢視登入情況,發現好幾個終端依然登著,但是ip地址變化了,好吧,很有可能是網路ip地址變化導致xshell自動斷開連線。於是修改本機ip為固定地址發現就不會輕易斷了。

root     pts/3        183.186.203.80   Sat Aug 26 09:41   still logged in   
root     pts/2        171.127.72.216   Sat Aug 26 09:33   still logged in   
root     pts/2        118.77.199.116   Sat Aug 26 09:30 - 09:32  (00:01)    
root     pts/1        171.127.203.17   Sat Aug 26 09:05   still logged in   
root     pts/1        118.77.199.229   Fri Aug 25 09:16 - 09:30  (00:14)   

本人修改本機IP為固定地址了,還是不能解決問題。繼續經過多次BAIDU和艱苦摸索,終於找到了解決辦法:

一、修改配置檔案: 

如果本機網路dns變化也會導致xshell自動斷開連線,這種情況通過修改ssh配置檔案將其中“UseDNS yes”去掉註釋並改成no即可,過程如下。

vim /etc/ssh/sshd_config 

將UseDNS yes 改為 no,儲存。

UseDNS no

二、重新更改ssh配置目錄和檔案的許可權(為了安全系統配置檔案勿隨意開放為所有許可權) 

cd /etc/ssh

sudo chmod 644 ./*
sudo chmod 600 ssh_host_dsa_key
sudo chmod 600 ssh_host_rsa_key
sudo chmod 755 .

修改完配置記得重新啟動ssh

/etc/init.d/sshd restart

三、也有網友把許可權設定為如下樣子也可以了的

  • 修改ssh許可權 
    chmod 400 /etc/ssh/*
  • 重啟SSH 
    service sshd restart
  • 重啟閘道器 
    service network restart

四、沒有設定超時時間

  相關文章:http://blog.csdn.net/zgl07/article/details/40424637

解決方案是:    

sudo vim /etc/ssh/sshd_config

新增兩行:    

ClientAliveInterval 60
ClientAliveCountMax 3

然後

sudo /etc/init.d/sshd restart

 

相關文章