如何从 SSH 获取输出

How to get output from SSH

我已经获得了将命令列表发送到 SSH 服务器并写入输出的代码。 对于某些命令,我​​需要检查具有预期值的输出。 我尝试以多种方式做到这一点,但我认为我遗漏了一些东西。 如何正确完成?

            JSch jsch = new JSch();
            Session session = jsch.getSession(username, hostname, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Thread.sleep(2000);

            Channel channel = session.openChannel("shell");

            List<String> commands = new ArrayList<String>();
            commands.add("ls");
            commands.add("cd Downloads");
            commands.add("pwd");
            commands.add("ls");

            channel.setOutputStream(System.out);
            channel.setInputStream(System.in);
            PrintStream shellStream = new PrintStream(channel.getOutputStream());
            channel.connect(15 * 1000);

            for (String command : commands) {
                if (command == "pwd") {
                    //if output not equal to "home/rooot/Downloads"
                    break;
                }

                shellStream.println(command);
                shellStream.flush();
            }

控制台有输出吗?

如果有,也许你可以这样做。

/// ! I don't test the code,  any question ,reply me.

// new stream for receive data. 
ByteArrayOutputStream tmpOutput = new ByteArrayOutputStream();
channel.setOutputStream(tmpOutput);
channel.setInputStream(System.in);
PrintStream shellStream = new PrintStream(channel.getOutputStream());
String currentWorkDirectory = null; 

// ... omit your code 

for (String command : commands) {

    shellStream.println(command);
    shellStream.flush();

    Thread.sleep(15);  // sleep 15ms, wait for output. maybe not very rigorous
    // read output 
    String commandOutput = tmpOutput.toString();

    // clear and reset stream
    tmpOutput.reset();

    if (command == "pwd") {
        //if output not equal to "home/rooot/Downloads"
        currentWorkDirectory = commandOutput;

        if(currentWorkDirectory != "home/rooot/Downloads"){
            break;
        }
    }

}