Java Code Examples for com.trilead.ssh2.Session#getStderr()

The following examples show how to use com.trilead.ssh2.Session#getStderr() . 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: SSHCmdHelper.java    From cosmic with Apache License 2.0 4 votes vote down vote up
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 2
Source File: SSHCmdHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
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 3
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
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 4
Source File: TestClientWithAPI.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
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();
            }
        }
    }
}