SSH connection with Java

2019-01-10 12:30发布

问题:

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?

回答1:

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


回答2:

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



回答3:

Take a look at Jaramiko.



回答4:

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



回答5:

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



回答6:

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



回答7:

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();