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

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

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.


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

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
  • Excellent, I thought I had read through the entire man page, but I somehow missed that option. I must need to clean my glasses or something.
    – Zoredache
    Aug 8 '11 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.