用OPENSSH过程连接服务器时,经常遇到长时间不操作而被服务器踢出的情况,常见的提示如:

Write failed: Broken pipe
一开始还以为是内网的问题呢
这是因为如果有一段时间在SSH连接上无数据传输,连接就会断开。解决此问题有两种方法。

方案一:在客户端设置(前提,你的办公本本或者pc 是os 是一个linux)
在客户端电脑上编辑(需要root权限)

sudo vi /etc/ssh/ssh_config

并添加如下一行:

ServerAliveInterval 60

此后该系统里的用户连接SSH时,每60秒会发一个KeepAlive请求,避免被踢。

方案二:在服务器端设置
如果有相应的权限,也可以在服务器端设置,即编辑/etc/ssh/sshd_config,并添加:

echo "ClientAliveInterval 60">>/etc/ssh/sshd_config

; and then restart the sshd
重启OPENSSH服务器后该项设置会生效。每一个连接到此服务器上的客户端都会受其影响。应注意启用该功能后,安全性会有一定下降(比如忘记登出时……),所以 建议用客户端设置

如果您只想让当前的 ssh 保持连接,可以使用以下的命令:

$ ssh -o ServerAliveInterval=60 user@sshserver

更加详细的
当用SSH Secure Shell连接Linux时,如果几分钟没有任何操作,连接就会断开。必须重新登陆才行,每次都重复相同的操作,很是烦人,一般修改两个地方可将这烦人的问题解决

1、echo $TMOUT
如果显示空白,表示没有设置, 等于使用默认值0, 一般情况下应该是不超时. 如果大于0, 可以在如/etc/profile之类文件中设置它为0.
Definition: TMOUT: If set to a value greater than zero, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if input does not arrive

2、修改/etc/ssh/sshd_config文件,将ClientAliveInterval 0和ClientAliveCountMax 3的注释符号去掉,将ClientAliveInterval对应的0改成60,ClientAliveInterval指定了服务器端向客户端请求消息的时间间隔, 默认是0, 不发送.而ClientAliveInterval 60表示每分钟发送一次, 然后客户端响应, 这样就保持长连接了.ClientAliveCountMax, 使用默认值3即可.ClientAliveCountMax表示服务器发出请求后客户端没有响应的次数达到一定值, 就自动断开. 正常情况下, 客户端不会不响应.
想参考更多,请输入man sshd_config了解更多信息

#操作命令
echo “ClientAliveInterval 60″>>/etc/ssh/sshd_config; and then restart the sshd

下面是man sshd_config获取的描述信息
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.

ClientAliveCountMax
Sets the number of client alive messages (see above) which may
be sent without sshd receiving any messages back from the
client. If this threshold is reached while client alive mes-
sages are being sent, sshd will disconnect the client, terminat-
ing the session. It is important to note that the use of client
alive messages is very different from TCPKeepAlive (below). The
client alive messages are sent through the encrypted channel and
therefore will not be spoofable. The TCP keepalive option
enabled by TCPKeepAlive is spoofable. The client alive mecha-
nism is valuable when the client or server depend on knowing
when a connection has become inactive.
The default value is 3. If ClientAliveInterval (above) is set
to 15, and ClientAliveCountMax is left at the default, unrespon-
sive ssh clients will be disconnected after approximately 45
seconds.

http://www.osedu.net/article/linux/2012-05-02/405.html

参考资料
https://bbs.archlinux.org/viewtopic.php?id=97003
http://yunwei.blog.51cto.com/381136/432672