use of com.trilead.ssh2.Session in project CloudStack-archive by CloudStack-extras.
the class ConfigTest method executeTest.
public boolean executeTest() {
int error = 0;
Element rootElement = this.getInputFile().get(0).getDocumentElement();
NodeList commandLst = rootElement.getElementsByTagName("command");
//Analyze each command, send request and build the array list of api commands
for (int i = 0; i < commandLst.getLength(); i++) {
Node fstNode = commandLst.item(i);
Element fstElmnt = (Element) fstNode;
//new command
ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
if (api.getName().equals("rebootManagementServer")) {
s_logger.info("Attempting to SSH into management server " + this.getParam().get("hostip"));
try {
Connection conn = new Connection(this.getParam().get("hostip"));
conn.connect(null, 60000, 60000);
s_logger.info("SSHed successfully into management server " + this.getParam().get("hostip"));
boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password");
return false;
}
String restartCommand = "service cloud-management restart; service cloud-usage restart";
Session sess = conn.openSession();
s_logger.info("Executing : " + restartCommand);
sess.execCommand(restartCommand);
Thread.sleep(120000);
sess.close();
conn.close();
} catch (Exception ex) {
s_logger.error(ex);
return false;
}
} else {
//send a command
api.sendCommand(this.getClient(), null);
//verify the response of the command
if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200) && (api.getTestCaseInfo() != null)) {
s_logger.error("Test case " + api.getTestCaseInfo() + "failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
error++;
} else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
//set parameters for the future use
if (api.setParam(this.getParam()) == false) {
s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
return false;
} else {
//verify parameters
if (api.verifyParam() == false) {
s_logger.error("Command " + api.getName() + " failed. Verification for returned parameters failed. Command was sent with url " + api.getUrl());
error++;
} else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
}
}
} else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url " + api.getUrl() + " Required: " + api.getRequired());
if (api.getRequired() == true) {
s_logger.info("The command is required for the future use, so exiging");
return false;
}
error++;
} else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed - test passed. Command was sent with url " + api.getUrl());
}
}
}
if (error != 0)
return false;
else
return true;
}
use of com.trilead.ssh2.Session in project CloudStack-archive by CloudStack-extras.
the class EventsApiTest method executeTest.
public boolean executeTest() {
int error = 0;
Element rootElement = this.getInputFile().get(0).getDocumentElement();
NodeList commandLst = rootElement.getElementsByTagName("command");
//Analyze each command, send request and build the array list of api commands
for (int i = 0; i < commandLst.getLength(); i++) {
Node fstNode = commandLst.item(i);
Element fstElmnt = (Element) fstNode;
//!!!check if we need to execute mySql command
NodeList commandName = fstElmnt.getElementsByTagName("name");
Element commandElmnt = (Element) commandName.item(0);
NodeList commandNm = commandElmnt.getChildNodes();
if (((Node) commandNm.item(0)).getNodeValue().equals("mysqlupdate")) {
//establish connection to mysql server and execute an update command
NodeList mysqlList = fstElmnt.getElementsByTagName("mysqlcommand");
for (int j = 0; j < mysqlList.getLength(); j++) {
Element itemVariableElement = (Element) mysqlList.item(j);
s_logger.info("Executing mysql command " + itemVariableElement.getTextContent());
try {
Statement st = this.getConn().createStatement();
st.executeUpdate(itemVariableElement.getTextContent());
} catch (Exception ex) {
s_logger.error(ex);
return false;
}
}
} else if (((Node) commandNm.item(0)).getNodeValue().equals("agentcommand")) {
//connect to all the agents and execute agent command
NodeList commandList = fstElmnt.getElementsByTagName("commandname");
Element commandElement = (Element) commandList.item(0);
NodeList ipList = fstElmnt.getElementsByTagName("ip");
for (int j = 0; j < ipList.getLength(); j++) {
Element itemVariableElement = (Element) ipList.item(j);
s_logger.info("Attempting to SSH into agent " + itemVariableElement.getTextContent());
try {
Connection conn = new Connection(itemVariableElement.getTextContent());
conn.connect(null, 60000, 60000);
s_logger.info("SSHed successfully into agent " + itemVariableElement.getTextContent());
boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password");
return false;
}
Session sess = conn.openSession();
s_logger.info("Executing : " + commandElement.getTextContent());
sess.execCommand(commandElement.getTextContent());
Thread.sleep(60000);
sess.close();
conn.close();
} catch (Exception ex) {
s_logger.error(ex);
return false;
}
}
} else {
//new command
ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
//send a command
api.sendCommand(this.getClient(), null);
//verify the response of the command
if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200)) {
s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
error++;
} else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
//verify if response is suppposed to be empty
if (api.getResponseType() == ResponseType.EMPTY) {
if (api.isEmpty() == true) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Empty response was returned as expected. Command was sent with url " + api.getUrl());
} else {
s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Empty response was expected. Command was sent with url " + api.getUrl());
}
} else {
if (api.isEmpty() != false)
s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Non-empty response was expected. Command was sent with url " + api.getUrl());
else {
//set parameters for the future use
if (api.setParam(this.getParam()) == false) {
s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
return false;
} else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
}
}
}
} else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url " + api.getUrl());
if (api.getRequired() == true) {
s_logger.info("The command is required for the future use, so exiging");
return false;
}
error++;
} else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed. Command was sent with url " + api.getUrl());
}
}
}
//verify events with userid parameter - test case 97
HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
expectedEvents.put("VM.START", 1);
boolean eventResult = ApiCommand.verifyEvents(expectedEvents, "INFO", "http://" + this.getParam().get("hostip") + ":8096", "userid=" + this.getParam().get("userid1") + "&type=VM.START");
s_logger.info("Test case 97 - listEvent command verification result is " + eventResult);
//verify error events
eventResult = ApiCommand.verifyEvents("../metadata/error_events.properties", "ERROR", "http://" + this.getParam().get("hostip") + ":8096", this.getParam().get("erroruseraccount"));
s_logger.info("listEvent command verification result is " + eventResult);
if (error != 0)
return false;
else
return true;
}
use of com.trilead.ssh2.Session in project ACS by ACS-Community.
the class Executor method remotePortable.
/**
* @return false - if this failed gracefully
* @throws IOException - if this failed severely
*/
private static boolean remotePortable(String username, String password, String command, String endMark, NativeCommand.Listener listener, String host) throws IOException {
if (listener == null) {
// normalization: use a do-nothing implementation
listener = new NativeCommand.ListenerAdapter();
}
try {
remoteFlow.reset(null);
// connect
// --------
Connection conn = new Connection(host);
connections.add(conn);
conn.connect();
remoteFlow.success(RemoteFlow.CONNECT);
// login
// ------
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed");
remoteFlow.success(RemoteFlow.LOG_IN);
// send command
// -------------
Session sess = conn.openSession();
sessions.add(sess);
/* msc 2008-11:
* We're passing the command as an argument to ssh, just like typing
* > ssh 127.0.0.1 "env"
* on the commandline. This opens a non-login shell on the remote host
* which (thank you bash) won't parse the .bash_profile but only the .bashrc!
* Now unfortunately the usual setup for accounts on Alma machines is to
* have the ACS settings defined in .bash_profile. The optimal way around
* this would be to run a real login shell here by allocating a terminal,
* and then deal with all the input output/stuff ourselves. I'm trying here
* to get away with something cheaper: Explicitly source the .bash_profile
* before running the command.
*/
command = ". ~/.bash_profile ; " + command;
log.info("Now sending: '" + command + "'");
sess.execCommand(command);
remoteFlow.success(RemoteFlow.SEND_COMMAND);
// read output, scan for endmark
// ----------------------------
SearchBuffer searchStdout = null;
SearchBuffer searchStderr = null;
if (endMark != null) {
searchStdout = new SearchBuffer(endMark);
searchStderr = new SearchBuffer(endMark);
}
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if (stdout.available() == 0 && stderr.available() == 0) {
/* Even though currently there is no data available, it may be that new data arrives
* and the session's underlying channel is closed before we call waitForCondition().
* This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may be set together. */
int conditions = sess.waitForCondition(//
ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, // allow several seconds
10 * 1000);
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
throw new IOException("Timeout while waiting for data from peer");
}
if ((conditions & ChannelCondition.EOF) != 0) {
/* The remote side won't send us further data ... */
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
/* ... and we have consumed all data in the local arrival window. */
break;
}
}
/* At this point, either STDOUT_DATA or STDERR_DATA, (or both) is set. */
}
/* If you below use "if" instead of "while", then the way the output appears on the local
* stdout and stder streams is more "balanced". Addtionally reducing the buffer size
* will also improve the interleaving, but performance will slightly suffer.
* OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
*/
if (stdout.available() > 0) {
int len = stdout.read(buffer);
listener.stdoutWritten(null, new String(buffer, 0, len));
if (searchStdout != null)
if (searchStdout.add(buffer, 0, len)) {
remoteFlow.success(RemoteFlow.COMPLETE);
break;
}
}
if (stderr.available() > 0) {
int len = stderr.read(buffer);
// msc 2008-11: porting to a different ssh library. this should of course
// call stderrWritten() but i don't want to change the original behavior.
listener.stdoutWritten(null, new String(buffer, 0, len));
if (searchStderr != null)
if (searchStderr.add(buffer, 0, len)) {
remoteFlow.success(RemoteFlow.COMPLETE);
break;
}
}
}
return true;
} catch (IOException exc) {
remoteFlow.failure(exc);
/* throw exc; */
return false;
}
}
use of com.trilead.ssh2.Session in project zm-mailbox by Zimbra.
the class RemoteManager method execute.
public synchronized RemoteResult execute(String command) throws ServiceException {
Session s = null;
try {
s = getSession();
if (ZimbraLog.rmgmt.isDebugEnabled())
ZimbraLog.rmgmt.debug("executing shim command '" + mShimCommand + "' on " + this);
s.execCommand(mShimCommand);
OutputStream os = s.getStdin();
String send = "HOST:" + mHost + " " + command;
if (ZimbraLog.rmgmt.isDebugEnabled()) {
ZimbraLog.rmgmt.debug("sending mgmt command '%s' on %s", send, this);
}
os.write(send.getBytes());
os.close();
RemoteResult result = new RemoteResult();
InputStream stdout = new StreamGobbler(s.getStdout());
InputStream stderr = new StreamGobbler(s.getStderr());
result.mStdout = ByteUtil.getContent(stdout, -1);
result.mStderr = ByteUtil.getContent(stderr, -1);
if (ZimbraLog.rmgmt.isTraceEnabled()) {
try {
ZimbraLog.rmgmt.trace("stdout content for cmd:\n%s", new String(result.mStdout, "UTF-8"));
ZimbraLog.rmgmt.trace("stderr content for cmd:\n%s", new String(result.mStderr, "UTF-8"));
} catch (Exception ex) {
ZimbraLog.rmgmt.trace("Problem logging stdout or stderr for cmd - probably not UTF-8");
}
}
try {
result.mExitStatus = s.getExitStatus();
} catch (NullPointerException npe) {
// wow this is strange - on hold command we hit NPE here. TODO file a bug against ganymed
}
if (result.mExitStatus != 0) {
throw new IOException("command failed: exit status=" + result.mExitStatus + ", stdout=" + new String(result.mStdout) + ", stderr=" + new String(result.mStderr));
}
result.mExitSignal = s.getExitSignal();
return result;
} catch (IOException ioe) {
throw ServiceException.FAILURE("exception executing command: " + command + " with " + this, ioe);
} finally {
if (s != null) {
releaseSession(s);
}
}
}
use of com.trilead.ssh2.Session in project zm-mailbox by Zimbra.
the class RemoteManager method executeBackground0.
private synchronized void executeBackground0(String command, RemoteBackgroundHandler handler) {
Session s = null;
try {
s = getSession();
if (ZimbraLog.rmgmt.isDebugEnabled())
ZimbraLog.rmgmt.debug("(bg) executing shim command '" + mShimCommand + "' on " + this);
s.execCommand(mShimCommand);
OutputStream os = s.getStdin();
String send = "HOST:" + mHost + " " + command;
if (ZimbraLog.rmgmt.isDebugEnabled())
ZimbraLog.rmgmt.debug("(bg) sending mgmt command '" + send + "' on " + this);
os.write(send.getBytes());
os.close();
InputStream stdout = new StreamGobbler(s.getStdout());
InputStream stderr = new StreamGobbler(s.getStderr());
handler.read(stdout, stderr);
} catch (OutOfMemoryError e) {
Zimbra.halt("out of memory", e);
} catch (Throwable t) {
handler.error(t);
} finally {
if (s != null) {
releaseSession(s);
}
}
}
Aggregations