4

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?

Tom Freezers
  • 227
  • 3
  • 9
  • You can do `while /bin/true; do ssh -N ...; done` - this would restart the ssh process whenever the tunnel fails. Whenever you reboot the server - does that mean a graceful reset or a hard one? If graceful, try terminating the ssh client with `TERM` signal before rebooting (should be done automatically, but probably is not happening) – Misko Sep 28 '16 at 21:07
  • The ssh connection is established, but it can't open port 2222 on the remote server since that's in use. I want the tunnel to not establish if it can't bind to that port. I'm doing a graceful reboot. – Tom Freezers Sep 28 '16 at 22:07

1 Answers1

4

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.

ngj
  • 883
  • 7
  • 17