与 Java 的 SSH 连接

2022-09-01 05:18:27

如何在 Java 中连接到 SSH 服务器?我不需要/不想要一个外壳。我只想连接到SSH服务器并获取的内容,例如, .我该怎么做?file.txt


答案 1

使用 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();
        }
    }
}

输出:

Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt

答案 2

Java本身不支持它,但你可以使用像JSch这样的库来做到这一点。


推荐