Knowing if a remote port forward was successful?

2019-02-23 03:38发布

问题:

I am trying to setup some reverse ssh tunnels so I can access my home network by bouncing off some server with a public IP.

When I run this command: ssh -R :[port_XX]:localhost:22 some_user@my_server

Even if "port_XX" is in use, it will still make a successful ssh connection to "my_server".

If I am running this command directly, I can see the problem when it gives me a warning: "Warning: remote port forwarding failed for listen port [port_XX]"

However, I am starting this ssh session inside a screen session using a cron job.

How can I programmatically check if the remote port forwarding was successful?

The screen session can be checked with "screen -ls", the ssh session is also easily checked, but the remote port forwarding...?

(Please let me know if this question is not clear enough! I've done my research but haven't found a simple solution.)

回答1:

Try adding -o ExitOnForwardFailure=yes

The full command will be something like:

ssh -N -R [port_XX]:localhost:22 -o ExitOnForwardFailure=yes user@host

(-N is useful to just forward port, without opening a remote shell; you can also add -f to send process in background, no need if you are running under screen, though..)