36

How can I connect to an SSH server in Java? I don't need/want a shell. I just want to connect to the SSH server and get the content of, say, file.txt. How can I do that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user348041
  • 361
  • 1
  • 3
  • 3

8 Answers8

50

Use JSch

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * @author World
 */
public class SSHReadFile {

    public static void main(String args[]) {
        String user = "john";
        String password = "mypassword";
        String host = "192.168.100.23";
        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.");

            InputStream inputStream = sftpChannel.get(remoteFile);

            try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
            }
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
}

output:

Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt
Niko
  • 4,158
  • 9
  • 46
  • 85
World
  • 2,007
  • 7
  • 27
  • 37
  • 1
    Great answer worked for me but just make sure to close everything you open. session.disconnect and sftpChannel.quit . – Joseph Cox Dec 16 '15 at 19:49
  • When invoking the constructor the following exception is thrown: `GRAVE: JSF1073: se ha interceptado javax.faces.event.AbortProcessingException durante el procesamiento de INVOKE_APPLICATION 5 : UIComponent-ClientId=tipoMovimientoGrid:j_idt15, Mensaje=java.lang.ClassCircularityError: com/jcraft/jsch/JSchException java.lang.ClassCircularityError: com/jcraft/jsch/JSchException at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:178)` – 0x777 Aug 24 '16 at 17:53
  • getting the error while trying to connect windows server: com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect – Elango Mani Oct 03 '17 at 11:31
5

Java doesn't support that natively, but you can use a library like JSch to do it

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
1

You must use a third-party library - JSch is one of them. Google with "Java ssh" and you will get plenty of other options.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1

You could check JSSH, which is a Java SSH library.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fortega
  • 19,463
  • 14
  • 75
  • 113
  • Hi.. I need to add some parameters in my ssh command, like ssh -v user@ip, can u tell me how can I do using this Library – Saurabh Verma Feb 28 '19 at 07:48
1

http://www.ganymed.ethz.ch/ssh2/ implements a ssh2 client in Java. I use it for port forwarding.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • " Please note: ETH Zurich does not maintain the code anymore. Please visit the following website, code.google.com/p/ganymed-ssh-2/, in case you need updates " – Muhammed Refaat Aug 14 '16 at 13:45
0

Take a look at Jaramiko.

Brian Clapper
  • 25,705
  • 7
  • 65
  • 65
0

Not 100% sure but I believe that the sockets have a great deal to do with ssh connections unless you are attempting to do a pre-installed command manipulation application. There are numerous outside packages that you can use to achieve this goal, but if you want to do your own socket creation, it's going to take a large amount of reading and deciphering/encrypting to get this done.

Also creating your own socket is dangerous if not done correctly with the right protocols and security specifications, so be wary about doing so until you are 100% sure you're capable of committing to learning enough.

-3

I used this and worked for me

Channel channel=session.openChannel("exec");
String command = "Your Command here";
((ChannelExec)channel).setCommand(command);

InputStream in=channel.getInputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Zyad
  • 5
  • 1