ssh -R with port 0: let the server pick the port, and find out which one
ssh -R 0:host:port asks the server for any free port. ssh prints "Allocated port N for remote forward", and with -O forward the number alone, for scripts.
A remote forward normally names the port the server listens on. If any free port will do, ask for port 0 and the server picks one:
ssh -R 0:localhost:3000 user@server
Where the port number appears
The server sends the chosen port back, and ssh reports it on your side:
Allocated port 49152 for remote forward to localhost:3000
ssh writes this as a log message (standard error), at the default log level. With -q (quiet) it is not shown.
Getting the number in a script
With connection sharing, ask an already running master connection to add the forward. ssh then prints just the port number on standard output:
ssh -M -S ~/.ssh/ctl-%C -fN user@server
port=$(ssh -S ~/.ssh/ctl-%C -O forward -R 0:localhost:3000 user@server)
-M starts the master, -S names its control socket, -fN puts it in the background with no remote command, and -O forward sends the new forward to it.
On the server
To see the port on the server itself, list the listening sockets, for example ss -tlnp on Linux, and look for the ssh server process.
When it fails
The server can refuse a remote forward of any port, 0 included, for the same reasons as a fixed one. Add -o ExitOnForwardFailure=yes to make ssh exit instead of carrying on without the forward. See SSH "remote port forwarding failed for listen port": why ssh -R is refused.
This app's remote forward needs a server port from 1 to 65535, so it cannot ask the server to pick one with port 0. See Port forwarding.
Related
- Port forwarding: local, remote, dynamic
- SSH "remote port forwarding failed for listen port": why ssh -R is refused
- bind_address in ssh -L and ssh -R: localhost, * and GatewayPorts
- Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd