如何从SSH获取输出

问题描述 投票:-2回答:1

我有代码将命令列表发送到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();
            }
java jsch
1个回答
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;
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.