use of com.trilead.ssh2.Session in project cloudstack by apache.
the class SshHelper method sshExecute.
public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile, String password, String command, int connectTimeoutInMs, int kexTimeoutInMs, 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)) {
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)) {
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);
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
StringBuffer sbResult = new StringBuffer();
int currentReadBytes = 0;
while (true) {
throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
if ((stdout.available() == 0) && (stderr.available() == 0)) {
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));
}
}
String result = sbResult.toString();
if (StringUtils.isBlank(result)) {
try {
result = IOUtils.toString(stdout, StandardCharsets.UTF_8);
} catch (IOException e) {
s_logger.error("Couldn't get content of input stream due to: " + e.getMessage());
return new Pair<Boolean, String>(false, result);
}
}
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<Boolean, String>(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<Boolean, String>(false, result);
}
return new Pair<Boolean, String>(true, result);
} finally {
if (sess != null)
sess.close();
if (conn != null)
conn.close();
}
}
use of com.trilead.ssh2.Session in project cloudstack by apache.
the class SshHelperTest method canEndTheSshConnectionTest.
@Test
public void canEndTheSshConnectionTest() throws Exception {
PowerMockito.spy(SshHelper.class);
Session mockedSession = Mockito.mock(Session.class);
PowerMockito.doReturn(true).when(SshHelper.class, "isChannelConditionEof", Mockito.anyInt());
Mockito.when(mockedSession.waitForCondition(ChannelCondition.EXIT_STATUS, 1l)).thenReturn(0);
PowerMockito.doNothing().when(SshHelper.class, "throwSshExceptionIfConditionsTimeout", Mockito.anyInt());
SshHelper.canEndTheSshConnection(1, mockedSession, 0);
PowerMockito.verifyStatic();
SshHelper.isChannelConditionEof(Mockito.anyInt());
SshHelper.throwSshExceptionIfConditionsTimeout(Mockito.anyInt());
Mockito.verify(mockedSession).waitForCondition(ChannelCondition.EXIT_STATUS, 1l);
}
use of com.trilead.ssh2.Session in project cloudstack by apache.
the class ConfigTest method executeTest.
@Override
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 intellij-community by JetBrains.
the class Session method requestX11Forwarding.
/**
* Request X11 forwarding for the current session.
* <p>
* You have to supply the name and port of your X-server.
* <p>
* This method may only be called before a program or shell is started in
* this session.
*
* @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
* @param port the port of the real (target) X11 server (e.g., 6010)
* @param cookie if non-null, then present this cookie to the real X11 server
* @param singleConnection if true, then the server is instructed to only forward one single
* connection, no more connections shall be forwarded after first, or after the session
* channel has been closed
* @throws IOException
*/
public void requestX11Forwarding(String hostname, int port, byte[] cookie, boolean singleConnection) throws IOException {
if (hostname == null)
throw new IllegalArgumentException("hostname argument may not be null");
synchronized (this) {
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_x11_requested)
throw new IOException("X11 forwarding was already requested.");
if (flag_execution_started)
throw new IOException("Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
flag_x11_requested = true;
}
/* X11ServerData - used to store data about the target X11 server */
X11ServerData x11data = new X11ServerData();
x11data.hostname = hostname;
x11data.port = port;
x11data.x11_magic_cookie = cookie;
/* if non-null, then present this cookie to the real X11 server */
/* Generate fake cookie - this one is used between remote clients and our proxy */
byte[] fakeCookie = new byte[16];
String hexEncodedFakeCookie;
while (true) {
rnd.nextBytes(fakeCookie);
/* Generate also hex representation of fake cookie */
StringBuffer tmp = new StringBuffer(32);
for (int i = 0; i < fakeCookie.length; i++) {
String digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
}
hexEncodedFakeCookie = tmp.toString();
if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
break;
}
/* Ask for X11 forwarding */
cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
synchronized (this) {
if (flag_closed == false) {
this.x11FakeCookie = hexEncodedFakeCookie;
cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
}
}
/* Now it is safe to start remote X11 programs */
}
use of com.trilead.ssh2.Session in project intellij-community by JetBrains.
the class BasicWithHTTPProxy method main.
public static void main(String[] args) {
String hostname = "my-ssh-server";
String username = "joe";
String password = "joespass";
String proxyHost = "192.168.1.1";
// default port used by squid
int proxyPort = 3128;
try {
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* We want to connect through a HTTP proxy */
conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
// if the proxy requires basic authentication:
// conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
/* Now connect (through the proxy) */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
Aggregations