ssh port forwarding, ssh tunnels


ssh may be used to connect to a server process on a remote machine and make the remote port accessible on the local machine as if the server process ran locally. This is called "port forwarding" or "ssh tunneling".

ssh -L [<local interface>:]<local port>:<remote interface>:<remote port> <remote host>

Note that the <remote interface> is the ip address where the connection seems to enter the remote host and not the address of the remotely accessible interface on the remote host.
So if you want that the server process on the remote host thinks that the client coming through the ssh tunnel is locally connected, you need to set <remote interface> to localhost.

Example:

ssh -N -f -L localhost:3306:localhost:3306 azug.minpet.unibas.ch

Builds the tunnel to the mysql server port (3306) via the local interface of azug.minpet.unibas.ch and makes the mysql server port on the local machine available for a locally running mysql client.

The -N option inhibits the execution of a remote command which by default would be a shell.
The -f option brings the ssh program into background.

mysql -h localhost --protocol=TCP -P 3306 -u <user> -p <db_name>

then connects to the database <db_name> on azug.minpet.unibas.ch.

Note:
localhost for the local interface at IP address 127.0.0.1 does not always work.


ssh reverse tunnels


ssh also allows to build up tunnels that work in the reverse direction of the one used to initiate the tunnel. This may be useful for example if you want to connect to a server service running on a machine which is located in a local network behind a NAT router.

Example:

ssh -nNT -R 22022:localhost:22 user@azug.minpet.unibas.ch

This builds a tunnel from the remote machine (azug.minpet.unibas.ch) to the local machine. This tunnel forwards a client connecting to port 22022 at azug.minpet.unibas.ch to port 22 at the machine which initiated the tunnel and is not directly reachable, because it is located behind a NAT router.

This means that you get connected to the ssh daemon of the tunnel initiating machine by connecting with an ssh client to port 22022 at azug.minpet.unibas.ch.

line
linux logo Powered by Apache
line
This site maintained by:
lukas.zimmermann@unibas.ch
My public PGP key
last updated: 2017-07-12 Valid CSS! Valid XHTML 1.0 Strict