2

So, I have a nice bit of code (that I'm struggling to understand), that allows me to send a command to my server, and get one line of response. The code works, but I would like to get multiple lines back from the server.

The main class is:

JSch jSch = new JSch();
MyUserInfo ui = new MyUserInfo();
String Return = "Error";
try {
    String host = "Username@HostName";
    String user = host.substring(0, host.indexOf('@'));
    host = host.substring(host.indexOf('@') + 1);
    Session rebootsession = jSch.getSession(user, host, 22);
    rebootsession.setPassword(Password);
    rebootsession.setUserInfo(ui);
    rebootsession.connect();
    Channel channel = rebootsession.openChannel("exec");
    ((ChannelExec) channel).setCommand(Command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0) break;
            Return = new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    rebootsession.disconnect();
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
}
return Return;

I would like to be able to return multiple lines from the first class. Any help would be greatly appreciated!

2
  • I don't understand what you want back? Can you put an example? Commented Feb 1, 2017 at 15:40
  • The answer below solved the issue, however an example would be when i used the lshw command, it only returned a single line, not the entire config. Thanks anyway! Commented Feb 2, 2017 at 12:33

1 Answer 1

1

You have to concatenate the output to the Return variable, instead of overwriting it in each pass:

Return += new String(tmp, 0, i);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.