19

I want to create an SSH Tunnel in Java. I noticed quite a few Java SSH libraries on another post. Before I dig into each option, maybe someone can give me some code snippets of how they did it or at least tell me which client library would work best.

I only need tunneling. I won't need stuff like file transfers, terminal emulation, etc. Is there a simple few lines of code that can forward a port on the server to work on my client's localhost adapter? Ideally both client and server would be in Java, but I'll settle for just client for now.

Community
  • 1
  • 1
User1
  • 39,458
  • 69
  • 187
  • 265
  • NB: This question was also informative on this subject matter: http://stackoverflow.com/questions/3954454/fast-implementation-of-a-port-forward-in-java – Jay Taylor Aug 13 '12 at 21:41
  • here is an example I put together on another similar question http://stackoverflow.com/a/16023513/311525 – Scott May 18 '13 at 15:38

2 Answers2

26

Well, as pointed out in the other question, JSch is indeed a great choice and has several examples here. The PortForwardingL.java class might be a good starting point.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • I like the BSD license on this library. Thank you for pointing me directly to the sample I needed to see! – User1 Nov 05 '09 at 15:20
22

You can do this with several libraries. My favorite is the ssh library inside MindTerm package,

http://linuxmafia.com/pub/java/ISNetworks-MindTerm-1.2.1-SCP3.tar.gz

You can open a tunneled connection like this,

  SSHSocketFactory fact = new SSHSocketFactory(sshHost, sshPort, new SSHPasswordAuthenticator(sshUser, sshPassword));

  sock = fact.createSocket(host, port);
ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
  • 3
    +1 Wow. This is very simple. Too bad the license is kind of strange (my bad for not mentioning I need something BSD-like). I tried to accept this also as an answer, but SO only allows one answer. I at least upvoted your answer. Thanks for your help. – User1 Nov 05 '09 at 15:22