Get incoming ssh forwarded connection port number

143 views Asked by At

I have a server who is forwarding connections to a set of other servers.

Here I forward all incomming connections on:

my.tunnel.com:33199 to my.server2.com:52222

And..

my.tunnel.com:33200 to my.server3.com:52222

.. until

my.tunnel.com:XXXXX to my.serverN.com:52222

I'm initiating this by the following command on each server, except the tunnel my.tunnel.com:

ssh -o StrictHostKeyChecking=no -l root -i /etc/ssh/id_rsa -R *:33199:127.0.0.1:22 -p 443 my.tunnel.com 0 33199

...

ssh -o StrictHostKeyChecking=no -l root -i /etc/ssh/id_rsa -R *:XXXXX:127.0.0.1:22 -p 443 my.tunnel.com 0 XXXXX

Well, this works fine!

But!

At the point of the launching of each of these commands I'd like to check on my.tunnel.com that my.server2.com wants my.tunnel.com to forward exactly from port 33199, but not another port! So at this point I'd like to get this port number.

Please let me know if the problem is still not enough clearly exposed.

Thanks!

1

There are 1 answers

1
Tomas On BEST ANSWER

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