1

I would like to use ssh with port forwarding by default. So I added the following ssh command to a script (with made-up server names):

ssh -f -N user@server -L 8080:server:8080

where server is a remote server. Everything works except that if the script is run a second time, ssh complains that

bind [127.0.0.1]:8080: Address already in use

Is there a way to tell ssh to test and do the port-forwarding only when the port/address is available?

2
  • 1
    @Kamil I don't see that your possible dupe answers the question at all.
    – roaima
    Apr 7 at 6:12
  • Doing nothng would answer the letter of the question: the 2nd ssh will complain, but it's non-fatal. So it would "do the port-forwarding only when the port/address is available". So if the question isn't a dupe, then OP should give more details. Eg: if the 2nd time "server" isn't the same, it would make some sense to ask something. See also: xyproblem.info
    – A.B
    Apr 7 at 7:05
0

After some search, I found from wikibooks that the testing can be done by:

  1. creating the port-forwarding with a ControlMaster file

ssh -f -N -M -S /tmp/ssh_pf_%r-%h-%p -L 8080:127.0.0.1:8080 server

and,

  1. testing with the ControlMaster file if the connection is already made:

ssh -O check -S /tmp/ssh_pf_%r-%h-%p server

Put together, the following will make the connection only if the it hasn't been made already (I guess, saving a second attempt to connect):

if ! ssh -O check -S /tmp/ssh_pf_%r-%h-%p server ;
then ssh -f -N -M -S /tmp/ssh_pf_%r-%h-%p -L 8080:127.0.0.1:8080 server ; fi

As pointed out in this answer, using the ControlMaster file also allows to easily close the connection as follows:

ssh -O exit -S /tmp/ssh_pf_%r-%h-%p server

There may be better alternatives, but this seems to work so far.

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