SSH接続を維持する方法
しばらく 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
参考文献
- What do options
ServerAliveInterval
andClientAliveInterval
in sshd_config do exactly? - ssh_config(5) - Linux man page
- sshd_config(5) - Linux man page