Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to open a SSH tunnel using Java?

Tags:

java

ssh

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)

like image 395
Smain Avatar asked Mar 17 '11 08:03

Smain


People also ask

Can you SSH with Java?

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.

How do I browse through SSH tunnel?

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.

What are the 3 types of SSH tunneling?

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.

How do I run a Java program on a remote machine?

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.


2 Answers

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);
like image 161
WhiteFang34 Avatar answered Sep 30 '22 07:09

WhiteFang34


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

like image 40
Sacx Avatar answered Sep 30 '22 07:09

Sacx