SSH超时断开连接的解决办法
2012-06-01 09:35:25 阿炯

OpenSSH在使用的时候,几分钟不在终端上不操作的话就会自动断开连接,这是出于安全的考虑,但对于需要长时间使用的用户来说很麻烦,每次都要重新连接。解决方法如下:

将/etc/ssh/sshd_config中的“ClientAliveInterval”设置取消注释,并把0改为一个较小的数值即可。
echo 'ClientAliveInterval 30
ClientAliveCountMax 6' >> /etc/ssh/sshd_config && /etc/init.d/ssh reload

具体说明参看下面的解释:
ClientAliveInterval
Using an OpenSSH server's ClientAliveInterval, it is possible for the ssh server to send periodic "keep alive" messages to the ssh client, keeping the connection open indefinitely. This is useful when a firewall or other packet filtering device drops idle connections after a certain period of time. Note that this is different from the KeepAlive directive in ssh_config.

From the sshd_config manpage:
ClientAliveInterval
Sets a timeout interval in seconds after which if no data has been received from the client, sshd will send a message through the encrypted channel to request a response from the client.   The default is 0, indicating that these messages will not be sent to the client.   This option applies to protocol version 2 only.

Example (send "keep alive" messages every 5 minutes) on Red Hat Linux:
1. Add ClientAliveInterval 300 to /etc/ssh/sshd_config

2. Reload the sshd server configuration with /sbin/service sshd reload

Note: you may want to configure the ClientAliveCountMax value in sshd_config to set the number of times that "keep alive" messages are sent. If ClientAliveCountMax number of "keep alive" messages are not acknowledged by the ssh client, the connection is terminated by the ssh server. The default value of 3 should be sufficient for most users.

注意:您可能需要配置ClientAliveCountMax,这个sshd_config中的值来设置“keep alive”消息被发送的次数。如果ClientAliveCountMax数量的“keep alive”消息不被ssh客户端所响应,那么ssh服务器将终止连接,默认值3应当满足大部分用户。

仔细总结有多种发现原因,环境变量TMOUT引起,ClientAliveCountMax和ClientAliveInterval设置问题或者甚至是防火墙的设置问题,所以可以这么尝试:

1, echo $TMOUT
如果显示空白,表示没有设置,等于使用默认值0,一般情况下应该是不超时,如果大于0,可以在如/etc/profile或主目录中相关文件中将它设置为0.

2. ClientAliveInterval
在/etc/ssh/sshd_config中增加ClientAliveInterval 60,ClientAliveInterval指定了服务器端向客户端请求消息的时间间隔,默认是0,不发送;而ClientAliveInterval 60表示每分钟发送一次,然后客户端响应,这样就保持长连接了。这里不是客户端主动发起保持连接的请求,而是需要服务器先主动。

另外,至于ClientAliveCountMax, 使用默认值3即可,ClientAliveCountMax表示服务器发出请求后客户端没有响应的次数达到一定值,,就自动断开, 正常情况下,客户端不会不响应。

3. 启用ssh客户端的 keepalive
putty -> Connection -> Seconds between keepalives ( 0 to turn off ),默认为0,改为60。
xshell -> Connection -> Keep Alive 页面中也有相关设置(这个在建立新会话属性时是默认开启的,不过在实际使用过程中并没有生效,还是要在服务器上进行设置)。

上述3个方法应该能解决问题,如果不行,请参考sshd_config的man手册。在修改了ssd_config 重置ssh server:'/etc/rc.d/init.d/sshd reload'。