session.setPassword(password);
}
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// Direct stderr output of command
InputStream err = ((ChannelExec) channel).getErrStream();
InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
Reader errStrBufRdr = new BufferedReader(errStrRdr);
// Direct stdout output of command
InputStream out = channel.getInputStream();
InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
Reader outStrBufRdr = new BufferedReader(outStrRdr);
StringBuffer stdout = new StringBuffer();
StringBuffer stderr = new StringBuffer();
channel.connect(5000); // timeout after 5 seconds
while (true) {
if (channel.isClosed()) {
break;
}
// Read from both streams here so that they are not blocked,
// if they are blocked because the buffer is full, channel.isClosed() will never
// be true.
int ch;
while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
// In case there's still some more stuff in the buffers, read them
int ch;
while ((ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
while ((ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
// After the command is executed, gather the results (both stdin and stderr).
result.append(stdout.toString());
result.append(stderr.toString());
// Shutdown the connection
channel.disconnect();
session.disconnect();
}
catch(Throwable e){
e.printStackTrace();
// Return empty string if we can't connect.