14

I have a bash script that runs ssh to create a port forward, using a command like this:

ssh -N -i keyfile -L 1000:localhost:22 *remote_ip*

There are occasions where the listen port may be busy, so this command gives the error:

channel_setup_fwd_listener: cannot listen to port: 1000
Could not request local forwarding.

However, the ssh connection remains up and the ssh command blocks. How can I make ssh actually fail when this occurs, so my script can handle it?

Unfortunately, I also need to support this on Solaris (Intel), and the ssh command there doesn't support the ExitOnForwardFailure option - any ideas in this case?

xorsyst
  • 251
  • 2
  • 7

3 Answers3

22

If you check the ssh man page, you'll find there is a config option called ExitOnForwardFailure and you can specify it on the command line by adding:

-o "ExitOnForwardFailure yes"

All the ssh config options are described in the ssh_config and sshd_config man pages. If you find the option is not supported, you may have to upgrade to a newer version of ssh.

Good Luck.

etherfish
  • 1,757
  • 10
  • 12
  • Thanks, that wasn't in the man page I googled, but is available to my ssh. – xorsyst Feb 24 '14 at 10:38
  • Does this option really work? I still have a "warning: remote port forwarding failed" and an established connection... – greg Dec 06 '16 at 07:04
  • 1
    It seems it doesn't fail it it can bind one port even if another port fails: securityfocus.com/archive/121/505298/30/480/threaded – greg Dec 06 '16 at 07:11
3

You can also add ExitOnForwardFailure yes into your '~/.ssh/config' file.

Create one if you haven't got one.

Make sure the correct user owns the file.

Restart your ssh service sudo service ssh restart on unbuntu.

SteveT
  • 31
  • 1
  • `sudo service ssh restart` is about restarting ssh daemon and has nothing to do with ssh client configuration which is stored in `$HOME/.ssh/config`. – Victor Yarema Nov 27 '20 at 08:36
0

Only ExitOnForwardFailure may not enough.

Try use -o ExitOnForwardFailure=yes, -o ServerAliveInterval=10 and -o ServerAliveCountMax=3 to make a stable fail.

For example, to remote forward psql and ssh:


ssh -NC -o ExitOnForwardFailure=yes \
-o ServerAliveInterval=10 \
-o ServerAliveCountMax=3 \
-R remote_dev_ip:5432:127.0.0.1:5432 \
-R remote_dev_ip:2222:127.0.0.1:22 \
tun@remote_dev

Reference