When you need to make a SSH connection to connect to a server, you can create a left tunnel (a left port forwarding) to reach the server as of it was direct reachable.
Illustration: Image Credit: How does reverse SSH tunneling work? from Erik
- When you need to make a connection to a private database (in a private network), you can a SSH tunnel and reach it as of the database was local.
Create the tunnel
You can create the tunnel with any client such as:
- or jsch
Create the tunnel: From the client host:
ssh -N -T -l loginName -L8881:farAwayServer:8888 sshServerHost
- localhost is the host seen from the ssh client
- The local port is 8881 (The port of your machine)
- farAwayServer is the server to reach (it can be the sshServerHost)
- The server port is 8888
- The loginName is loginName
- N means no remote command
- T disables pseudo-tty allocation (No terminal)
Jsch is a java library.
JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); localPort = 4321; remoteHost = "localhost"; remotePort = 3306; session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); session.connect(); int assigned_port = session.setPortForwardingL(localPort, remoteHost, remotePort);