如何从SSH获取输出

时间:2019-03-27 12:45:50

标签: java jsch

我有将命令列表发送到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();
            }

1 个答案:

答案 0 :(得分:1)

控制台中是否有任何输出?

如果有的话,也许您可​​以这样做。

/// ! 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;
        }
    }

}