I need to establish an arbitrary remote-forwarded port to a specific local port when connecting to a server. I don't have admin rights on the server, which is a significant compute resource used by a large number of people. I can't pick a static remote port number, because I have no reason to expect that it will always be available.
I am using a command like ssh -R 0:localhost:8001 servername
-- using 0 for the port number, so the remote server can pick a port for me. This works well; the client tells me the allocated port number and I can then use it to make a connection back to my machine (or another on my network) manually.
The problem is that I need to write some scripts for others to use on the remote system, and I need a means to determine on the remote end what the port number is for that session. I've looked at the SSH_* environment variables in the session and none of them are helpful. I've tried looking through the output of ss -le | grep "uid:$UID"
and that does find the port among others, but it seems a bit convoluted and not really certain to always work, especially if the user happens to have other processes running, perhaps in different login sessions.
Is there a definitive, less messy way to find a dynamically allocated remote forwarded port number?
Edit: I just discovered this is a duplicate of this earlier post, where the question was asked in slightly different terms but is exactly the same thing. Unfortunately I can't make use of solutions that involve root or sudo on the server.
I'm gathering that what I want may not be possible to do in a reliable way -- making this automatic port selection a much less useful feature.