如何保持 ssh 连接处于活动状态

如果 ssh 服务器和客户端之间一段时间内没有发送消息,那么 ssh 连接很快就会终止,这有时会很烦人,但是有一些方法可以让它在客户端或服务器端长时间或永远保持活动状态。

From the server side

Open and edit the /etc/ssh/sshd_config on the ssh server

ClientAliveInterval 60
ClientAliveCountMax 0

where ClientAliveInterval can be set to a value greater than 0, meaning the interval seconds to request client messages from the server and setting to 0 means doing nothing and disabling the requests; and ClientAliveCountMax can be set to a value greater than 0, meaning maximum counts of intervals without receiving client messages and setting to 0 means no maximum count limit and the server does not terminate the connection even without receiving any messages from the client.

For example, below combination will keep the connection alive for at least 60 * 3 = 180 seconds before server terminates the session.

ClientAliveInterval 60
ClientAliveCountMax 3

after the change, restart the sshd service to make it take effect

service sshd restart

From the client side

Create a ~/.ssh/config on the ssh client machine (e.g. laptops)

HOST *
 ServerAliveInterval 60
 ServerAliveCountMax 0

The meaning of the config options is similar to the ones from the server side, varying in that who is the side that is trying to keep the connection alive.

Alternatively pass the options via command line during connection

ssh -o ServerAliveInterval=60 user@instance-1

参考资料

linux