When creating reverse tunnels on recent versions of OpenSSH, a remote port of 0 can be given to bind any available port:
-R [bind_address:]port:host:hostport
...
If the port argument is `0', the listen port will be dynamically allocated on the server and reported to the client at run time. …
Source: OpenSSH client manpage
My question is: how can I (in an automated way) determine this port allocation on the server? It seems rather unhelpful that it is reported to the host running the ssh client – but not to the target, which will want to make connections to this port to access services on the client.
Two similar options I can think of are either running
# netstat -ntlp
on the server and looking for suspect ports bound on 127.0.0.1 by sshd or by looking at the output of
# lsof -p $PPID | grep TCP | grep LISTEN
But neither of these is pleasant from an automation point of view, and there isn't any way of tying the dynamic ports back to the origin service port if more than one such tunnel is created.
Is there anything I'm missing to effectively get a list of active tunnels (both local and remote port numbers) on the sshd server side, like an equivalent to the SSH_CONNECTION environment variable, but for active tunnels?
For some context, I'm trying to create potentially very many simultaneous reverse tunnels to a host, tunnelling back to the same port number on many different hosts. Having the TCP stack automatically manage the port pool seems like the most effective way of doing this.