Search in sources :

Example 21 with Session

use of com.google.spanner.v1.Session in project intellij-community by JetBrains.

the class StdoutAndStderr method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    String password = "joespass";
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* Now connect */
        conn.connect();
        /* Authenticate */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");
        InputStream stdout = new StreamGobbler(sess.getStdout());
        InputStream stderr = new StreamGobbler(sess.getStderr());
        BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
        BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
        System.out.println("Here is the output from stdout:");
        while (true) {
            String line = stdoutReader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        System.out.println("Here is the output from stderr:");
        while (true) {
            String line = stderrReader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 22 with Session

use of com.google.spanner.v1.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);
        }
    }
}
Also used : StreamGobbler(ch.ethz.ssh2.StreamGobbler) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) IOException(java.io.IOException) ServiceException(com.zimbra.common.service.ServiceException) Session(ch.ethz.ssh2.Session)

Example 23 with Session

use of com.google.spanner.v1.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);
        }
    }
}
Also used : StreamGobbler(ch.ethz.ssh2.StreamGobbler) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Session(ch.ethz.ssh2.Session)

Example 24 with Session

use of com.google.spanner.v1.Session in project cloudstack by apache.

the class SshHelper method openConnectionSession.

/**
     * It gets a {@link Session} from the given {@link Connection}; then, it waits
     * {@value #WAITING_OPEN_SSH_SESSION} milliseconds before returning the session, given a time to
     * ensure that the connection is open before proceeding the execution.
     */
protected static Session openConnectionSession(Connection conn) throws IOException, InterruptedException {
    Session sess = conn.openSession();
    Thread.sleep(WAITING_OPEN_SSH_SESSION);
    return sess;
}
Also used : Session(com.trilead.ssh2.Session)

Example 25 with Session

use of com.google.spanner.v1.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();
    }
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) IOException(java.io.IOException) Session(com.trilead.ssh2.Session) Connection(com.trilead.ssh2.Connection) Pair(com.cloud.utils.Pair)

Aggregations

Session (com.trilead.ssh2.Session)37 Connection (com.trilead.ssh2.Connection)31 IOException (java.io.IOException)24 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)5 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