58

If I do a remote port forward, a la -R 3690:localhost:3690 when a binding already exists on the port on the remote host, I get this warning:

Warning: remote port forwarding failed for listen port 3690

Is there a way to have ssh fail (i.e. exit with a nonzero return code), rather than just emit a warning?

Matt Joiner
  • 1,102

3 Answers3

94

Run

ssh -o ExitOnForwardFailure=yes ...

or put

ExitOnForwardFailure yes

into ~/.ssh/config. See man ssh_config for details.

1

I use bash script on the target host to make sure the forwarding was opened correctly. The SSH connection will run this and exit if there's a problem with the port forwarding, e.g.

client side script: ( this uses .ssh/config for port forwarding settings )

#!/bin/bash    

while true; do
    echo -n starting at : "
    date
    ssh user@server bin/sshloop.sh
    echo "got back, sleeping 17 "
    sleep 17
done 

server side script ( bin/sshloop.sh )

#!/bin/bash

while true; do 
  echo $(date)" : SSH Reverse 1090:80, 1232:22 From Server to Client"
  sleep 17
  if ! netstat -an | grep -q ":::1090 " ; then
     echo "1090 forward missing, bailing out"
     exit
  fi
done

Maybe even run the client side script under screen with -dmS

0

Just trying to improve the accepted answer.

Indeed the answer is to use the ExitOnForwardFailure option:

ssh -o ExitOnForwardFailure=yes ...

But beware! When specifying the port forward as <port>:<ip>:<port>, ssh will attempt to bind to IPv6 (::1) and IPv4 (127.0.0.1), if either of those succeeds, it will not exit.

In most cases you will want ssh to exit if binding on IPv4 fails. In that case specify it explicitly using 0.0.0.0 or 127.0.0.1, e.g.:

ssh -o ExitOnForwardFailure=yes -L 0.0.0.0:3690:localhost:3690 ...
rustyx
  • 1,118