6

Is it possible to make a ssh connection to a server with java?

stivlo
  • 83,644
  • 31
  • 142
  • 199
Benni
  • 91
  • 1
  • 1
  • 7
  • 2
    Check [http://stackoverflow.com/questions/3071760/ssh-connection-with-java/9019095#9019095] – World Mar 08 '12 at 09:00
  • FWIW, I took a quick look at the ones listed below, and sshtools is only available under a GPL license. (jsch is available under BSD and sshJ is available under Apache.) – Mickalot May 20 '13 at 14:46

4 Answers4

4

Yes, I used http://sourceforge.net/projects/sshtools/ in a Java application to connect to a UNIX server over SSH, it worked quite well.

theomodsim
  • 69
  • 3
3

jsch and sshJ are both good clients. I'd personally use sshJ as the code is documented much more thoroughly.

jsch has widespread use, including in eclipse and apache ant. I've also had issues with jsch and AES encrypted private keys, which required re-encrypting in 3DES, but that could just be me.

ClutchDude
  • 997
  • 1
  • 9
  • 23
  • ok the jsch library worked fine and was very easy to implement. thank you for your answer. – Benni Jul 22 '10 at 20:34
2

Yes, it is possible. You can try the following code:

package mypackage;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;

public class SSHReadFile
    {
    public static void main(String args[])
    {
    String user = "user";
    String password = "password";
    String host = "yourhostname";
    int port=22;

    String remoteFile="/home/john/test.txt";

    try
        {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        session.connect();
            System.out.println("Connection established.");
        System.out.println("Crating SFTP Channel.");
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
        System.out.println("SFTP Channel created.");
        }
    catch(Exception e){System.err.print(e);}
    }
    }
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
1

To make connection to Java servers, you need an implementation of SSHD (ssh client is not enough). You can try Apache SSHD,

http://mina.apache.org/sshd/

Because sshd is already running on most systems, an easier alternative is to connect to the server through a SSH tunnel.

ZZ Coder
  • 74,484
  • 29
  • 137
  • 169