SSH – Make Failed Forward a Fatal Error

scriptingssh

I have a script which connects to a remote host to replicate some files via SSH. I must connect to an rsync daemon listening on port 873. To accomplish this I have a ssh configuration like this.

Host blah
    LocalForward 10873 127.0.0.1:873
    Hostname 10.2.4.1

Unfortunately because of the timing of this script, there is a small chance that on occasion when it attempts to establish the SSH session another similar script will have the port open to a different host.

If I connect while another ssh session is open I get the obvious message Address already in use.

me@local:~$ ssh blah
bind: Address already in use
channel_setup_fwd_listener: cannot listen to port: 10873
Could not request local forwarding.
Linux remote 2.6.26-2-amd64 #1 SMP Tue Jan 25 05:59:43 UTC 2011 x86_64
motd...
remote:~$ 

What I want to have happen is to have the SSH client immediately exit with a exit code so I can put some logic into my script to report a failure instead of trying to run any commands against the port forwarded to the incorrect host.

Best Answer

There's an ssh configuration option for it (from ssh_config(5)):

ExitOnForwardFailure
Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings. The argument must be ``yes'' or ``no''. The default is ``no''.

So in your ssh configuration you can add:

ExitOnForwardFailure yes

Or from the command-line:

$ ssh -o ExitOnForwardFailure=yes blah
Related Question