com.trilead.ssh2.Session Java Examples
The following examples show how to use
com.trilead.ssh2.Session.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SshHelperTest.java From cosmic with Apache License 2.0 | 6 votes |
@Test public void canEndTheSshConnectionTest() throws Exception { PowerMockito.spy(SshHelper.class); final 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); }
Example #2
Source File: SshHelperTest.java From cloudstack with Apache License 2.0 | 6 votes |
@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.class); SshHelper.isChannelConditionEof(Mockito.anyInt()); SshHelper.throwSshExceptionIfConditionsTimeout(Mockito.anyInt()); Mockito.verify(mockedSession).waitForCondition(ChannelCondition.EXIT_STATUS, 1l); }
Example #3
Source File: SshHelper.java From cosmic with Apache License 2.0 | 5 votes |
/** * Handles the SSH connection in case of timeout or exit. If the session ends with a timeout * condition, it throws an exception; if the channel reaches an end of file condition, but it * does not have an exit status, it returns true to break the loop; otherwise, it returns * false. */ protected static boolean canEndTheSshConnection(final int waitResultTimeoutInMs, final com.trilead.ssh2.Session sess, final int conditions) throws SshException { if (isChannelConditionEof(conditions)) { final int newConditions = sess.waitForCondition(ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs); throwSshExceptionIfConditionsTimeout(newConditions); if ((newConditions & ChannelCondition.EXIT_STATUS) != 0) { return true; } } return false; }
Example #4
Source File: SshHelper.java From cloudstack with Apache License 2.0 | 5 votes |
/** * Handles the SSH connection in case of timeout or exit. If the session ends with a timeout * condition, it throws an exception; if the channel reaches an end of file condition, but it * does not have an exit status, it returns true to break the loop; otherwise, it returns * false. */ protected static boolean canEndTheSshConnection(int waitResultTimeoutInMs, com.trilead.ssh2.Session sess, int conditions) throws SshException { if (isChannelConditionEof(conditions)) { int newConditions = sess.waitForCondition(ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs); throwSshExceptionIfConditionsTimeout(newConditions); if ((newConditions & ChannelCondition.EXIT_STATUS) != 0) { return true; } } return false; }
Example #5
Source File: SessionResult.java From hop with Apache License 2.0 | 4 votes |
public SessionResult( Session session ) throws HopException { readStd( session ); }
Example #6
Source File: SSHCmdHelper.java From cosmic with Apache License 2.0 | 4 votes |
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(); } } }
Example #7
Source File: SshHelper.java From cosmic with Apache License 2.0 | 4 votes |
protected static Session openConnectionSession(final Connection conn) throws IOException { return conn.openSession(); }
Example #8
Source File: SSHCmdHelper.java From cloudstack with Apache License 2.0 | 4 votes |
public static SSHCmdResult sshExecuteCmdOneShot(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException { s_logger.debug("Executing cmd: " + cmd.split(KeyStoreUtils.KS_FILENAME)[0]); 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 sbStdoutResult = new StringBuffer(); StringBuffer sbStdErrResult = 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); sbStdoutResult.append(new String(buffer, 0, currentReadBytes)); } while (stderr.available() > 0) { currentReadBytes = stderr.read(buffer); sbStdErrResult.append(new String(buffer, 0, currentReadBytes)); } } final SSHCmdResult result = new SSHCmdResult(-1, sbStdoutResult.toString(), sbStdErrResult.toString()); if (!Strings.isNullOrEmpty(result.getStdOut()) || !Strings.isNullOrEmpty(result.getStdErr())) { s_logger.debug("SSH command: " + cmd.split(KeyStoreUtils.KS_FILENAME)[0] + "\nSSH command output:" + result.getStdOut().split("-----BEGIN")[0] + "\n" + result.getStdErr()); } // exit status delivery might get delayed for(int i = 0 ; i<10 ; i++ ) { Integer status = sshSession.getExitStatus(); if( status != null ) { result.setReturnCode(status); return result; } Thread.sleep(100); } return result; } catch (Exception e) { s_logger.debug("Ssh executed failed", e); throw new SshException("Ssh executed failed " + e.getMessage()); } finally { if (sshSession != null) sshSession.close(); } }
Example #9
Source File: SshHelper.java From cloudstack with Apache License 2.0 | 4 votes |
protected static Session openConnectionSession(Connection conn) throws IOException, InterruptedException { Session sess = conn.openSession(); return sess; }
Example #10
Source File: SshTest.java From cloudstack with Apache License 2.0 | 4 votes |
public static void main(String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-h")) { host = iter.next(); } if (arg.equals("-p")) { password = iter.next(); } if (arg.equals("-u")) { url = iter.next(); } } if (host == null || host.equals("")) { s_logger.info("Did not receive a host back from test, ignoring ssh test"); System.exit(2); } if (password == null) { s_logger.info("Did not receive a password back from test, ignoring ssh test"); System.exit(2); } try { s_logger.info("Attempting to SSH into host " + host); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User + ssHed successfully into host " + host); boolean isAuthenticated = conn.authenticateWithPassword("root", password); if (isAuthenticated == false) { s_logger.info("Authentication failed for root with password" + password); System.exit(2); } String linuxCommand = "wget " + url; Session sess = conn.openSession(); sess.execCommand(linuxCommand); sess.close(); conn.close(); } catch (Exception e) { s_logger.error("SSH test fail with error", e); System.exit(2); } }
Example #11
Source File: StressTestDirectAttach.java From cloudstack with Apache License 2.0 | 4 votes |
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 " + s_account.get()); Thread.sleep(300000); } s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + s_account.get()); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User " + s_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 + " + s_account.get() + " executing : wget http://192.168.1.250/dump.bin"); sess.execCommand("wget http://192.168.1.250/dump.bin && dir dump.bin"); 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 (len > 0) // this check is somewhat paranoid s_logger.info(new String(buffer, 0, len)); } while (stderr.available() > 0) { /* int len = */stderr.read(buffer); } } sess.close(); conn.close(); if (success) { Thread.sleep(120000); return null; } else { retry++; if (retry == MAX_RETRY_WIN) { return "SSH Windows Network test fail for account " + s_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(); } } } }
Example #12
Source File: TestClientWithAPI.java From cloudstack with Apache License 2.0 | 4 votes |
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 " + s_account.get()); Thread.sleep(300000); } s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + s_account.get()); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User " + s_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 + " + s_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 (len > 0) // this check is somewhat paranoid 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 " + s_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(); } } } }
Example #13
Source File: GuestNetwork.java From cloudstack with Apache License 2.0 | 4 votes |
@Override public void run() { NDC.push("Following thread has started" + Thread.currentThread().getName()); int retry = 0; //Start copying files between machines in the network s_logger.info("The size of the array is " + this.virtualMachines.size()); while (true) { try { if (retry > 0) { s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt"); Thread.sleep(120000); } for (VirtualMachine vm : this.virtualMachines) { s_logger.info("Attempting to SSH into linux host " + this.publicIp + " with retry attempt: " + retry); Connection conn = new Connection(this.publicIp); conn.connect(null, 600000, 600000); s_logger.info("SSHed successfully into linux host " + this.publicIp); boolean isAuthenticated = conn.authenticateWithPassword("root", "password"); if (isAuthenticated == false) { s_logger.info("Authentication failed"); } //execute copy command Session sess = conn.openSession(); String fileName; Random ran = new Random(); fileName = Math.abs(ran.nextInt()) + "-file"; String copyCommand = new String("./scpScript " + vm.getPrivateIp() + " " + fileName); s_logger.info("Executing " + copyCommand); sess.execCommand(copyCommand); Thread.sleep(120000); sess.close(); //execute wget command sess = conn.openSession(); String downloadCommand = new String("wget http://172.16.0.220/scripts/checkDiskSpace.sh; chmod +x *sh; ./checkDiskSpace.sh; rm -rf checkDiskSpace.sh"); s_logger.info("Executing " + downloadCommand); sess.execCommand(downloadCommand); Thread.sleep(120000); sess.close(); //close the connection conn.close(); } } catch (Exception ex) { s_logger.error(ex); retry++; if (retry == retryNum) { s_logger.info("Performance Guest Network test failed with error " + ex.getMessage()); } } } }
Example #14
Source File: ConfigTest.java From cloudstack with Apache License 2.0 | 4 votes |
@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; }
Example #15
Source File: SessionResult.java From pentaho-kettle with Apache License 2.0 | 4 votes |
public SessionResult( Session session ) throws KettleException { readStd( session ); }