use of iaik.pkcs.pkcs11.Session in project cosmic by MissionCriticalCloud.
the class SshHelper method sshExecute.
public static Pair<Boolean, String> sshExecute(final String host, final int port, final String user, final File pemKeyFile, final String password, final String command, final int connectTimeoutInMs, final int kexTimeoutInMs, final int waitResultTimeoutInMs) throws Exception {
com.trilead.ssh2.Connection conn = null;
com.trilead.ssh2.Session sess = null;
try {
conn = new com.trilead.ssh2.Connection(host, port);
conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
if (pemKeyFile == null) {
if (!conn.authenticateWithPassword(user, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
} else {
if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
}
sess = openConnectionSession(conn);
sess.execCommand(command);
final InputStream stdout = sess.getStdout();
final InputStream stderr = sess.getStderr();
final byte[] buffer = new byte[8192];
final StringBuffer sbResult = new StringBuffer();
int currentReadBytes = 0;
while (true) {
throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
if ((stdout.available() == 0) && (stderr.available() == 0)) {
final int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs);
throwSshExceptionIfConditionsTimeout(conditions);
if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
break;
}
if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
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));
}
}
final String result = sbResult.toString();
if (sess.getExitStatus() == null) {
// Exit status is NOT available. Returning failure result.
s_logger.error(String.format("SSH execution of command %s has no exit status set. Result output: %s", command, result));
return new Pair<>(false, result);
}
if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
s_logger.error(String.format("SSH execution of command %s has an error status code in return. Result output: %s", command, result));
return new Pair<>(false, result);
}
return new Pair<>(true, result);
} finally {
if (sess != null) {
sess.close();
}
if (conn != null) {
conn.close();
}
}
}
use of iaik.pkcs.pkcs11.Session in project cosmic by MissionCriticalCloud.
the class SSHCmdHelper method sshExecuteCmdOneShotWithExitCode.
public static int sshExecuteCmdOneShotWithExitCode(final com.trilead.ssh2.Connection sshConnection, final 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);
final InputStream stdout = sshSession.getStdout();
final InputStream stderr = sshSession.getStderr();
final byte[] buffer = new byte[8192];
final 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)) {
final int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 120000);
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
final 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));
}
}
final 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++) {
final Integer status = sshSession.getExitStatus();
if (status != null) {
return status;
}
Thread.sleep(100);
}
return -1;
} catch (final Exception e) {
s_logger.debug("Ssh executed failed", e);
throw new SshException("Ssh executed failed " + e.getMessage());
} finally {
if (sshSession != null) {
sshSession.close();
}
}
}
use of iaik.pkcs.pkcs11.Session in project CloudStack-archive by CloudStack-extras.
the class TestClientWithAPI method sshWinTest.
private static String sshWinTest(String host) {
if (host == null) {
s_logger.info("Did not receive a host back from test, ignoring win ssh test");
return null;
}
// We will retry 5 times before quitting
int retry = 1;
while (true) {
try {
if (retry > 0) {
s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt. Account is " + _account.get());
Thread.sleep(300000);
}
s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + _account.get());
Connection conn = new Connection(host);
conn.connect(null, 60000, 60000);
s_logger.info("User " + _account.get() + " ssHed successfully into windows host " + host);
boolean success = false;
boolean isAuthenticated = conn.authenticateWithPassword("Administrator", "password");
if (isAuthenticated == false) {
return "Authentication failed";
} else {
s_logger.info("Authentication is successfull");
}
try {
SCPClient scp = new SCPClient(conn);
scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777");
s_logger.info("Successfully put wget.exe file");
} catch (Exception ex) {
s_logger.error("Unable to put wget.exe " + ex);
}
if (conn == null) {
s_logger.error("Connection is null");
}
Session sess = conn.openSession();
s_logger.info("User + " + _account.get() + " executing : wget http://" + downloadUrl);
String downloadCommand = "wget http://" + downloadUrl + " && dir dump.bin";
sess.execCommand(downloadCommand);
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if ((stdout.available() == 0) && (stderr.available() == 0)) {
int conditions = sess.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.");
return null;
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
success = true;
int len = stdout.read(buffer);
if (// this check is somewhat paranoid
len > 0)
s_logger.info(new String(buffer, 0, len));
}
while (stderr.available() > 0) {
/* int len = */
stderr.read(buffer);
}
}
sess.close();
conn.close();
if (success) {
return null;
} else {
retry++;
if (retry == MAX_RETRY_WIN) {
return "SSH Windows Network test fail for account " + _account.get();
}
}
} catch (Exception e) {
s_logger.error(e);
retry++;
if (retry == MAX_RETRY_WIN) {
return "SSH Windows Network test fail with error " + e.getMessage();
}
}
}
}
use of iaik.pkcs.pkcs11.Session in project CloudStack-archive by CloudStack-extras.
the class TestClientWithAPI method sshTest.
private static String sshTest(String host, String password, String snapshot_test) {
int i = 0;
if (host == null) {
s_logger.info("Did not receive a host back from test, ignoring ssh test");
return null;
}
if (password == null) {
s_logger.info("Did not receive a password back from test, ignoring ssh test");
return null;
}
// We will retry 5 times before quitting
String result = null;
int retry = 0;
while (true) {
try {
if (retry > 0) {
s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt. Account is " + _account.get());
Thread.sleep(120000);
}
s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry + ". Account is " + _account.get());
Connection conn = new Connection(host);
conn.connect(null, 60000, 60000);
s_logger.info("User + " + _account.get() + " ssHed successfully into linux host " + host);
boolean isAuthenticated = conn.authenticateWithPassword("root", password);
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password" + password);
return "Authentication failed";
}
boolean success = false;
String linuxCommand = null;
if (i % 10 == 0)
linuxCommand = "rm -rf *; wget http://" + downloadUrl + " && ls -al dump.bin";
else
linuxCommand = "wget http://" + downloadUrl + " && ls -al dump.bin";
Session sess = conn.openSession();
s_logger.info("User " + _account.get() + " executing : " + linuxCommand);
sess.execCommand(linuxCommand);
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if ((stdout.available() == 0) && (stderr.available() == 0)) {
int conditions = sess.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.");
return null;
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
success = true;
int len = stdout.read(buffer);
if (// this check is somewhat paranoid
len > 0)
s_logger.info(new String(buffer, 0, len));
}
while (stderr.available() > 0) {
/* int len = */
stderr.read(buffer);
}
}
sess.close();
conn.close();
if (!success) {
retry++;
if (retry == MAX_RETRY_LINUX) {
result = "SSH Linux Network test fail";
}
}
if (snapshot_test.equals("no"))
return result;
else {
Long sleep = 300000L;
s_logger.info("Sleeping for " + sleep / 1000 / 60 + "minutes before executing next ssh test");
Thread.sleep(sleep);
}
} catch (Exception e) {
retry++;
s_logger.error("SSH Linux Network test fail with error");
if ((retry == MAX_RETRY_LINUX) && (snapshot_test.equals("no"))) {
return "SSH Linux Network test fail with error " + e.getMessage();
}
}
i++;
}
}
use of iaik.pkcs.pkcs11.Session in project CloudStack-archive by CloudStack-extras.
the class SSHCmdHelper method sshExecuteCmdOneShotWithExitCode.
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();
}
}
Aggregations