I want to open up a SSH tunnel in a Java program, so that the rest of the system will also have access to the connection (e.g. if I forward a port for a database to the localhost I should be able to open the database in another program)... In other words what I need to do it to create a Java wrapper for something like the unix command ssh. However I need the program to be cross platform, so if possible I would like to use a library from Java.
Is this possible (I have been looking at different libraries, but have not been able to create the tunnel so the rest of the system can use it yet)
JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.
While the tunnel is active, you should be able to access the application through the secure SSH tunnel you created, by browsing to http://127.0.0.1:SOURCE-PORT/ or http://localhost:SOURCE-PORT/. Remember to replace SOURCE-PORT with the source port number specified.
Transporting arbitrary data streams over SSH sessions is also known as SSH tunneling. OpenSSH, a popular open-source SSH server, supports three types of tunneling features- local port forwarding, remote port forwarding, and dynamic port forwarding.
In the Host field, enter the IP address or domain name of the host where the Java program runs. If the program runs on the same machine as the workbench, enter localhost . In the Port field, enter the port where the remote VM accepts connections. Generally, this port is specified when the remote VM is launched.
The JSch library definitely makes this easy and supports port forwarding:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect(timeout);
session.setPortForwardingL(listenPort, destHost, destPort);
I had a success with article from beanizer based on Jcraft's Jsch. Here are more details: http://www.beanizer.org/site/index.php/en/Articles/Java-ssh-tunneling-with-jsch.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With