Search in sources :

Example 31 with Session

use of com.trilead.ssh2.Session in project cloudstack by apache.

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];
        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)) {
                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);
                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 (result != null && !result.isEmpty())
            s_logger.debug(cmd + " output:" + result);
        // exit status delivery might get delayed
        for (int i = 0; i < 10; i++) {
            Integer status = sshSession.getExitStatus();
            if (status != null) {
                return status;
            }
            Thread.sleep(100);
        }
        return -1;
    } catch (Exception e) {
        s_logger.debug("Ssh executed failed", e);
        throw new SshException("Ssh executed failed " + e.getMessage());
    } finally {
        if (sshSession != null)
            sshSession.close();
    }
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 32 with Session

use of com.trilead.ssh2.Session in project google-cloud-java by GoogleCloudPlatform.

the class SessionImplTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    SpannerImpl spanner = new SpannerImpl(rpc, 1, null);
    String dbName = "projects/p1/instances/i1/databases/d1";
    String sessionName = dbName + "/sessions/s1";
    DatabaseId db = DatabaseId.of(dbName);
    Session sessionProto = Session.newBuilder().setName(sessionName).build();
    Mockito.when(rpc.createSession(Mockito.eq(dbName), optionsCaptor.capture())).thenReturn(sessionProto);
    session = spanner.createSession(db);
    // We expect the same options, "options", on all calls on "session".
    options = optionsCaptor.getValue();
    Mockito.reset(rpc);
}
Also used : ByteString(com.google.protobuf.ByteString) Session(com.google.spanner.v1.Session) Before(org.junit.Before)

Example 33 with Session

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;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 34 with Session

use of com.trilead.ssh2.Session in project Payara by payara.

the class SSHLauncher method runCommandAsIs.

private int runCommandAsIs(String command, OutputStream os, List<String> stdinLines, String[] env) throws IOException, InterruptedException {
    if (logger.isLoggable(Level.FINER)) {
        logger.finer("Running command " + command + " on host: " + this.host);
    }
    openConnection();
    StringBuffer buff = new StringBuffer();
    if (env != null) {
        Session tempSession = connection.openSession();
        OutputStream ous = new ByteArrayOutputStream();
        exec(tempSession, "ps -p $$ | tail -1 | awk '{print $NF}'", ous, null);
        String prefix;
        if (ous.toString().contains("csh")) {
            logger.fine("CSH shell");
            prefix = "setenv";
        } else {
            logger.fine("BASH shell");
            prefix = "export";
        }
        for (String st : env) {
            String cmd = prefix + " " + st;
            buff.append(cmd).append(";");
        }
    }
    buff.append(command);
    final Session sess = connection.openSession();
    int status = exec(sess, buff.toString(), os, listInputStream(stdinLines));
    // XXX: Should we close connection after each command or cache it
    // and re-use it?
    SSHUtil.unregister(connection);
    connection = null;
    return status;
}
Also used : OutputStream(java.io.OutputStream) Session(com.trilead.ssh2.Session)

Example 35 with Session

use of com.trilead.ssh2.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();
            }
        }
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Session(com.trilead.ssh2.Session)

Aggregations

Session (com.trilead.ssh2.Session)37 Connection (com.trilead.ssh2.Connection)31 IOException (java.io.IOException)25 InputStream (java.io.InputStream)24 Session (org.neo4j.driver.v1.Session)16 Test (org.junit.Test)15 Driver (org.neo4j.driver.v1.Driver)14 CoreClusterMember (org.neo4j.causalclustering.discovery.CoreClusterMember)9 RoutingNetworkSession (org.neo4j.driver.internal.RoutingNetworkSession)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 Session (ch.ethz.ssh2.Session)6 SCPClient (com.trilead.ssh2.SCPClient)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)6 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 Transaction (org.neo4j.driver.v1.Transaction)5 Record (org.neo4j.driver.v1.Record)4 StreamGobbler (ch.ethz.ssh2.StreamGobbler)3 BufferedReader (java.io.BufferedReader)3