当反向 ssh 隧道突然/不干净地断开连接时,如何释放 SSH 服务器上的端口?

TCZ*_*TCZ 26 networking linux ssh tunnel

我们在客户的位置安装了一些硬件,该硬件连接到我们的 ssh 服务器并建立反向 ssh 隧道,以便我们可以访问多个客户端系统以进行监控。

一切正常,直到 SSH 会话断开连接。

发生这种情况时,在我们的 SSH 服务器上,反向隧道使用的端口会停留在 LISTENING 模式,当我们的远程硬件最终尝试自动重新连接并重新建立其隧道时,它会失败并显示错误

警告:侦听端口 XXXX 的远程端口转发失败

我通过尝试干净的断开连接和释放端口的过程来测试我们的 SSH 服务器或客户端是否存在问题。当我模拟连接失败(例如断开客户端硬件的以太网端口)时,我们遇到了我上面描述的相同问题。

处理这种情况的正确方法是什么?请记住,这些是反向隧道,因此无论发生什么都需要在 SSH 服务器上完成。理想情况下,我需要 ssh 服务器立即意识到托管隧道的 SSH 会话已关闭并释放它正在使用的端口。我想解决方案可能涉及终止相关的 SSH 进程,但我需要小心这一点,因为我们有多个客户端连接到同一个 ssh 服务器,我不想让它们脱机。

如此成熟,我确信 SSHD 有某种内置功能来处理这个问题,但我就是想不通。

请提供建议,这样我就不必再回到管理 Windows 机器上去了...

仅供参考:我在基于 Debian 的发行版上运行它。

小智 22

你必须ClientAliveInterval在你的sshd_config.

ClientAliveInterval 15
Run Code Online (Sandbox Code Playgroud)

参考:man sshd_config

ClientAliveCountMax
         Sets the number of client alive messages (see below) 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 (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 mechanism
         is valuable when the client or server depend on knowing when a
         connection has become inactive.

         The default value is 3.  If ClientAliveInterval (see below) is
         set to 15, and ClientAliveCountMax is left at the default,
         unresponsive SSH clients will be disconnected after approximately
         45 seconds.  This option applies to protocol version 2 only.

 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.  This option applies to protocol
         version 2 only.
Run Code Online (Sandbox Code Playgroud)

  • 继续我之前的评论,[这是一个相关问题](https://serverfault.com/questions/598490/ssh-fails-to-disconnect-after-interruption) 没有任何答案,和 [this](https: //bugs.debian.org/cgi-bin/bugreport.cgi?bug=202868) 和 [this](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=259780) 错误报告描述一个类似的问题,同样没有任何答案。即使 [this answer](https://unix.stackexchange.com/questions/268387/ssh-tunnels-force-new-tunnel-and-kill-old-session) 也为这个用例提出了相同的解决方案,作为一种应该有效但无效的解决方案 (2认同)