MyBBS
让ubuntu的ssh保持长时间连接 - Printable Version

+- MyBBS (https://bbs.mjjjd.eu.org)
+-- Forum: My Category (https://bbs.mjjjd.eu.org/forumdisplay.php?fid=1)
+--- Forum: VPS (https://bbs.mjjjd.eu.org/forumdisplay.php?fid=2)
+--- Thread: 让ubuntu的ssh保持长时间连接 (/showthread.php?tid=23)



让ubuntu的ssh保持长时间连接 - adahrzgj - 08-21-2022



Ubuntu下的ssh连接老是自己会断,一段时间不理它就会失去响应

  如何让ssh连接服务器或者ssh tunnel保持连接呢?

  其实也很方便,只要在/etc/ssh/ssh_config文件里加两个参数就行了

  1 TCPKeepAlive yes

  2 ServerAliveInterval 300

  前一个参数是说要保持连接,后一个参数表示每过5分钟发一个数据包到服务器表示“我还活着”

  如果你没有root权限,修改或者创建~/.ssh/ssh_config也是可以的

原理
其实,很简单。就是ssh客户端定时向服务端发送心跳包,证明自己活着。这样server端就不会主动把它断掉了。
做法

在/etc/ssh/ssh_config中添加两行配置。
代码:
TCPKeepAlive yes
ServerAliveInterval 300 #300秒发送一次心跳包

在/etc/ssh/sshd_config中添加两行配置。
代码:
ClientAliveInterval 60 #表示每60s发送一次心跳包
ClientAliveCountMax 300 #客户响应次数达到300,就断开连接

然后重启ssh服务即可。