Sunday, October 21, 2012

Multihop ssh tunneling from Windows to Linux

Suppose that you need to connect to a remote PostgreSQL Linux server and you have:
* a Local Windows Machine as a workstation
* an intermediate Linux ssh gateway to which we have a legitimate ssh access.  This machine happens to have its own PostgreSQL server running on port 5432.
* that remote Linux server running the targeted PostgreSQL instance you try to connect to.

You can use the following way to connect to the remote PostgreSQL instance - as a local host Windows service:


1. Install Putty plink.exe. This is just a simple program permitting raw ssh commands.
2. Open a command line and execute this:

plink -t -X -A -L 5432:127.0.0.1:5433 root@gatewayServer -P 22 ssh -L 5433:127.0.0.1:5432 -X -A root@remotePostgresqlServer


This essentially:
a. connects to the gateway in port 22 (change it using that -P parameter if port is different) and also port forwards the 5433 port to windows 5432 server. Notice that I used 5433 because I will port forward the remote PostgreSQL to the intermediary where an existing PostgreSQL is running on 5432. So, we need a different port

b. connects from intermediary to the remote server, forwarding remote 5432 to the intermediary's 5433 port

Running the above single line you have to enter two passwords: one for the intermediary, one for the remote.

Once entering the passwords, just use pgAdmin or your favorite PostgreSQL clientto connect to 127.0.0.1:5432.