1. sshd_config(5) - OpenBSD manual pages
  2. ssh - What do options ServerAliveInterval and ClientAliveInterval in sshd_config do exactly? - Unix & Linux Stack Exchange

问题描述

使用ssh连接服务器时,一段时间后出现自动断连,可通过修改sshd服务的相关配置修改。

配置文件的存放路径:/etc/ssh/sshd_config

参数说明

ClientAliveCountMax

Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. 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 mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive.

The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.

ClientAliveInterval

Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) 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.

ServerAliveIntervalServerAliveCountMax含义与上相同

应用实例

sshd服务中,通过xxxxAliveCountMaxxxxxAliveInterval参数设置客户端与服务器之间的连接超时时间

  1. xxxxAliveInterval表示客户端服务器发对方发送消息的时间间隔
  2. xxxxAliveCountMax表示允许的最大请求数量,如客服端向服务器发送了若干次后仍未收到响应则自动断开连接

本地使用ssh连接某主机时,本机承担客户端(Client)角色,所连接的主机为服务器(Server)角色

因此对客户端,需要设置对服务器的超时连接时间:

1
2
ServerAliveInterval 30
ServerAliveCountMax 120

服务器端,需设置对客户端的超时连接时间:

1
2
ClientAliveInterval 30
ClientAliveCountMax 120

使用ssh连接时也可以在$USER/.ssh/config中针对某个连接修改相关配置,而不需要做全局修改,如:

1
2
3
4
5
Host myhostshortcut
HostName myhost.com
User barthelemy
ServerAliveInterval 60
ServerAliveCountMax 10