Determining the reverse port tunnels

Darren Tucker dtucker at
Wed Apr 22 11:31:46 AEST 2015

On Wed, Apr 22, 2015 at 9:43 AM, Cary FitzHugh <cary.fitzhugh at>

> Hi all,
> If I were to connect to a system with a command like this:
> ssh -R *:0:localhost:3000 user at server
> Is there any way for openssh to tell my shell what ports it opened for me?
> i.e. what port on server is my localhost:3000 exposed to?
> I know that there is a stderr / stdout printout of the port, but wonder if
> there is a way to know in my shell.  Maybe an env var?

There's no general way to do this: port forwards can be added and deleted
at any time but the environment variables can only be set and shell startup

>   Maybe some grepping of netstat?

The parent process ID of your shell is the sshd that's listening, so
something like this should work:

lsof -p $PPID | grep LISTEN

or the equivalent with netstat if your platform can map port numbers to

The cleanest solution is probably using a control socket which returns the
port number to the client., something like

ssh -N -MS /tmp/ctl yourserver &
port=`ssh -S /tmp/ctl -O forward -R 0: yourserver`
ssh -S /tmp/ctl yourserver command --port $port
ssh -S /tmp/ctl -O exit yourserver

Darren Tucker (dtucker at
GPG key 8FF4FA69 / D9A3 86E9 7EEE AF4B B2D4  37C9 C982 80C7 8FF4 FA69
    Good judgement comes with experience. Unfortunately, the experience
usually comes from bad judgement.

More information about the openssh-unix-dev mailing list