简体   繁体   中英

Reverse ssh tunnel fails to bind to port when tunnel is torn down and restarted

I have a host that starts a reverse ssh tunnel upon bootup like this:

ssh -N -R 2222:localhost:22 root@10.1.2.6

It works great and the reverse tunnel is formed. But whenever I reboot the host, the remote server that the tunnel is built to says this:

Sep 28 13:13:59 kali sshd[4547]: error: bind: Address already in use
Sep 28 13:13:59 kali sshd[4547]: error: channel_setup_fwd_listener_tcpip: cannot listen to port: 2222

In order for me to resolve this I have to wait a few minutes for the old ssh tunnel to timeout, then find the new ssh connection and kill it, then when I rebuild the ssh tunnel it works fine.

Is there an ssh command or autossh command that does something like checks if the remote host can bind that port, if not, try again in a few seconds?

I believe I have run into the same issue as the original poster. I seem to have found the solution at the end of the accepted answer of this question :

If the client reconnect before the connection has terminated on the server, you can end up in a situation where the new ssh connection is live, but has no port forwardings. In order to avoid that, you need to use the ExitOnForwardFailure keyword on the client side.

I have thus added the following line to my /etc/ssh/ssh_config file at the client side:

ExitOnForwardFailure yes

According to the ssh man page , this option will cause "a client started with -f [to] wait for all remote port forwards to be successfully established before placing itself in the background".

This seems to cause ssh to fail when attempting to start an ssh tunnel immediately after killing one. The option thus enables repeating the attempt until the tunnel is correctly re-established.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM