return sshExecuteCmd(sshConnection, cmd, 3);
}
public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) throws sshException {
s_logger.debug("Executing cmd: " + cmd);
Session sshSession = null;
try {
sshSession = sshConnection.openSession();
// There is a bug in Trilead library, wait a second before
// starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html
Thread.sleep(1000);
if (sshSession == null) {
throw new sshException("Cannot open ssh session");
}
sshSession.execCommand(cmd);
InputStream stdout = sshSession.getStdout();
InputStream stderr = sshSession.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if (stdout == null || stderr == null) {
throw new sshException("stdout or stderr of ssh session is null");
}
if ((stdout.available() == 0) && (stderr.available() == 0)) {
int conditions = sshSession.waitForCondition(
ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA
| ChannelCondition.EOF, 120000);
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
s_logger.info("Timeout while waiting for data from peer.");
break;
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
stdout.read(buffer);
}
while (stderr.available() > 0) {
stderr.read(buffer);
}
}
if (buffer[0] != 0)
s_logger.debug(cmd + " output:" + new String(buffer));
Thread.sleep(1000);
return sshSession.getExitStatus();
} catch (Exception e) {
s_logger.debug("Ssh executed failed", e);
throw new sshException("Ssh executed failed " + e.getMessage());
} finally {
if (sshSession != null)
sshSession.close();
}
}