简体   繁体   中英

How to get output from SSH

I've got the code that send list of commands to SSH server and write output. With some of commands I need to check output with expected value. I tried to do it in many ways, but I think I'm missing something. How can this be done correctly?

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

Is there any output in console ?

If have, maybe you can do like this.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM