To get the forwarded port
There is no such information in the environmental variables, so you must pass it yourself:
ssh -R 33199:127.0.0.1:22 my.tunnel.com "export MY_FWD_PORT=33199; my_command"
(my_command is the script you want to run on the server). More information about passing variables - https://superuser.com/q/163167/93604
To get the source port
Look at the environment variable SSH_CONNECTION
in man ssh(1). Its meaning is:
source_ip source_port dest_ip dest_port
You probably want source_port
, so just get the second part of it:
echo $SSH_CONNECTION | awk '{ print $2 }'
or
echo $SSH_CONNECTION | cut -d" " -f 2