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];
StringBuffer sbResult = new StringBuffer();
int currentReadBytes = 0;
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 | ChannelCondition.EXIT_STATUS,
120000);
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
String msg = "Timed out in waiting SSH execution result";
s_logger.error(msg);
throw new Exception(msg);
}
if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
currentReadBytes = stdout.read(buffer);
sbResult.append(new String(buffer, 0, currentReadBytes));
}
while (stderr.available() > 0) {
currentReadBytes = stderr.read(buffer);
sbResult.append(new String(buffer, 0, currentReadBytes));
}
}
String result = sbResult.toString();
if (result != null && !result.isEmpty())
s_logger.debug(cmd + " output:" + result);
// exit status delivery might get delayed
for(int i = 0 ; i<10 ; i++ ) {
Integer status = sshSession.getExitStatus();
if( status != null ) {
return status;
}
Thread.sleep(100);
}
return -1;
} catch (Exception e) {
s_logger.debug("Ssh executed failed", e);
throw new SshException("Ssh executed failed " + e.getMessage());
} finally {
if (sshSession != null)
sshSession.close();
}
}