0

I have the exact same problem described here: SSH Output always empty

Unfortunately the accepted answer doesn't work for me, because

bufferedReader.readLine()

ends up in a loop, probably because of the missing end of line.

In addition I don't get why the code in the first posting doesn't work. Anyone with a deeper insight?

thx in advance

EDIT: if i do

while ((line = bufferedReader.readLine()) != null) {
    stringBuilder.append(line);
    stringBuilder.append('\n');
}

AFTER the ssh connection is closed, there is no endless loop, but the output is still empty...

stringBuilder.append(bufferedReader.read());

leads to -1 as output.

just:

stringBuilder.append(bufferedReader.readLine());

results in "null".

what is this madness? i don't get it...

1 Answer 1

2

Answer: I was reading the wrong stream AND had to close the connection afterwards.

JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, 22);
session.setPassword(password);

// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);

session.connect();

// SSH Channel
ChannelExec channelssh = (ChannelExec)
session.openChannel("exec");
InputStream inputStream = channelssh.getInputStream(); 

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;

/**/
// Execute command
channelssh.setCommand(command);
channelssh.connect();

while ((line = bufferedReader.readLine()) != null) {
    stringBuilder.append(line);
    stringBuilder.append('\n');
}

channelssh.disconnect();

return stringBuilder.toString();
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.