Search in sources :

Example 11 with Connection

use of com.trilead.ssh2.Connection in project ACS by ACS-Community.

the class Executor method remotePortable.

/**
    * @return false - if this failed gracefully
    * @throws IOException - if this failed severely
    */
private static boolean remotePortable(String username, String password, String command, String endMark, NativeCommand.Listener listener, String host) throws IOException {
    if (listener == null) {
        // normalization: use a do-nothing implementation
        listener = new NativeCommand.ListenerAdapter();
    }
    try {
        remoteFlow.reset(null);
        // connect
        // --------
        Connection conn = new Connection(host);
        connections.add(conn);
        conn.connect();
        remoteFlow.success(RemoteFlow.CONNECT);
        // login
        // ------
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed");
        remoteFlow.success(RemoteFlow.LOG_IN);
        // send command
        // -------------
        Session sess = conn.openSession();
        sessions.add(sess);
        /* msc 2008-11:
          * We're passing the command as an argument to ssh, just like typing
          * > ssh 127.0.0.1 "env" 
          * on the commandline. This opens a non-login shell on the remote host
          * which (thank you bash) won't parse the .bash_profile but only the .bashrc!
          * Now unfortunately the usual setup for accounts on Alma machines is to
          * have the ACS settings defined in .bash_profile. The optimal way around
          * this would be to run a real login shell here by allocating a terminal,
          * and then deal with all the input output/stuff ourselves. I'm trying here
          * to get away with something cheaper: Explicitly source the .bash_profile
          * before running the command.
          */
        command = ". ~/.bash_profile ; " + command;
        log.info("Now sending: '" + command + "'");
        sess.execCommand(command);
        remoteFlow.success(RemoteFlow.SEND_COMMAND);
        // read output, scan for endmark
        // ----------------------------
        SearchBuffer searchStdout = null;
        SearchBuffer searchStderr = null;
        if (endMark != null) {
            searchStdout = new SearchBuffer(endMark);
            searchStderr = new SearchBuffer(endMark);
        }
        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();
        byte[] buffer = new byte[8192];
        while (true) {
            if (stdout.available() == 0 && stderr.available() == 0) {
                /* Even though currently there is no data available, it may be that new data arrives
					 * and the session's underlying channel is closed before we call waitForCondition().
					 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may be set together. */
                int conditions = sess.waitForCondition(//
                ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, // allow several seconds
                10 * 1000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    throw new IOException("Timeout while waiting for data from peer");
                }
                if ((conditions & ChannelCondition.EOF) != 0) {
                    /* The remote side won't send us further data ... */
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        /* ... and we have consumed all data in the local arrival window. */
                        break;
                    }
                }
            /* At this point, either STDOUT_DATA or STDERR_DATA, (or both) is set. */
            }
            /* If you below use "if" instead of "while", then the way the output appears on the local
				 * stdout and stder streams is more "balanced". Addtionally reducing the buffer size
				 * will also improve the interleaving, but performance will slightly suffer.
				 * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
				 */
            if (stdout.available() > 0) {
                int len = stdout.read(buffer);
                listener.stdoutWritten(null, new String(buffer, 0, len));
                if (searchStdout != null)
                    if (searchStdout.add(buffer, 0, len)) {
                        remoteFlow.success(RemoteFlow.COMPLETE);
                        break;
                    }
            }
            if (stderr.available() > 0) {
                int len = stderr.read(buffer);
                // msc 2008-11: porting to a different ssh library. this should of course
                // call stderrWritten() but i don't want to change the original behavior.
                listener.stdoutWritten(null, new String(buffer, 0, len));
                if (searchStderr != null)
                    if (searchStderr.add(buffer, 0, len)) {
                        remoteFlow.success(RemoteFlow.COMPLETE);
                        break;
                    }
            }
        }
        return true;
    } catch (IOException exc) {
        remoteFlow.failure(exc);
        /* throw exc; */
        return false;
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) PreparedString(alma.acs.commandcenter.util.PreparedString) Session(com.trilead.ssh2.Session)

Example 12 with Connection

use of com.trilead.ssh2.Connection in project BookReader by JustWayward.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            logger.log(buffer.readString(charset));
            logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 13 with Connection

use of com.trilead.ssh2.Connection in project zm-mailbox by Zimbra.

the class RemoteManager method getSession.

private Session getSession() throws ServiceException {
    try {
        mConnection = new Connection(mHost, mPort);
        mConnection.connect();
        if (!mConnection.authenticateWithPublicKey(mUser, mPrivateKey, null)) {
            throw new IOException("auth failed");
        }
        return mConnection.openSession();
    } catch (IOException ioe) {
        if (mConnection != null) {
            mConnection.close();
        }
        throw ServiceException.FAILURE("exception during auth " + this, ioe);
    }
}
Also used : Connection(ch.ethz.ssh2.Connection) IOException(java.io.IOException)

Example 14 with Connection

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

the class OvmResourceBase method setupServer.

protected void setupServer() throws IOException {
    com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22);
    sshConnection.connect(null, 60000, 60000);
    if (!sshConnection.authenticateWithPassword(_username, _password)) {
        throw new CloudRuntimeException("Unable to authenticate");
    }
    SCPClient scp = new SCPClient(sshConnection);
    String configScriptName = "scripts/vm/hypervisor/ovm/configureOvm.sh";
    String configScriptPath = Script.findScript("", configScriptName);
    if (configScriptPath == null) {
        throw new CloudRuntimeException("Unable to find " + configScriptName);
    }
    scp.put(configScriptPath, "/usr/bin/", "0755");
    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "sh /usr/bin/configureOvm.sh preSetup")) {
        throw new CloudRuntimeException("Execute configureOvm.sh preSetup failed on " + _ip);
    }
    File tmp = new File(configScriptPath);
    File scriptDir = new File(tmp.getParent());
    File[] scripts = scriptDir.listFiles();
    for (int i = 0; i < scripts.length; i++) {
        File script = scripts[i];
        if (script.getName().equals("configureOvm.sh")) {
            continue;
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Copying " + script.getPath() + " to " + s_ovsAgentPath + " on " + _ip + " with permission 0644");
        }
        scp.put(script.getPath(), s_ovsAgentPath, "0644");
    }
    sshConnection = SSHCmdHelper.acquireAuthorizedConnection(_ip, _username, _password);
    if (sshConnection == null) {
        throw new CloudRuntimeException(String.format("Cannot connect to ovm host(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, _password));
    }
    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "sh /usr/bin/configureOvm.sh postSetup")) {
        throw new CloudRuntimeException("Execute configureOvm.sh postSetup failed on " + _ip);
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Connection(com.cloud.ovm.object.Connection) File(java.io.File)

Example 15 with Connection

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

the class ScpTemplateDownloader method download.

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    if (_status == Status.ABORTED || _status == Status.UNRECOVERABLE_ERROR || _status == Status.DOWNLOAD_FINISHED) {
        return 0;
    }
    _resume = resume;
    _start = System.currentTimeMillis();
    URI uri;
    try {
        uri = new URI(_downloadUrl);
    } catch (URISyntaxException e1) {
        _status = Status.UNRECOVERABLE_ERROR;
        return 0;
    }
    String username = uri.getUserInfo();
    String queries = uri.getQuery();
    String password = null;
    if (queries != null) {
        String[] qs = queries.split("&");
        for (String q : qs) {
            String[] tokens = q.split("=");
            if (tokens[0].equalsIgnoreCase("password")) {
                password = tokens[1];
                break;
            }
        }
    }
    int port = uri.getPort();
    if (port == -1) {
        port = 22;
    }
    File file = new File(_toFile);
    com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(uri.getHost(), port);
    try {
        if (_storage != null) {
            file.createNewFile();
            _storage.setWorldReadableAndWriteable(file);
        }
        sshConnection.connect(null, 60000, 60000);
        if (!sshConnection.authenticateWithPassword(username, password)) {
            throw new CloudRuntimeException("Unable to authenticate");
        }
        SCPClient scp = new SCPClient(sshConnection);
        String src = uri.getPath();
        _status = Status.IN_PROGRESS;
        scp.get(src, _toDir);
        if (!file.exists()) {
            _status = Status.UNRECOVERABLE_ERROR;
            s_logger.debug("unable to scp the file " + _downloadUrl);
            return 0;
        }
        _status = Status.DOWNLOAD_FINISHED;
        _totalBytes = file.length();
        String downloaded = "(download complete)";
        _errorString = "Downloaded " + _remoteSize + " bytes " + downloaded;
        _downloadTime += System.currentTimeMillis() - _start;
        return _totalBytes;
    } catch (Exception e) {
        s_logger.warn("Unable to download " + _downloadUrl, e);
        _status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        _errorString = e.getMessage();
        return 0;
    } finally {
        sshConnection.close();
        if (_status == Status.UNRECOVERABLE_ERROR && file.exists()) {
            file.delete();
        }
        if (callback != null) {
            callback.downloadComplete(_status);
        }
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) URISyntaxException(java.net.URISyntaxException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) File(java.io.File)

Aggregations

Connection (com.trilead.ssh2.Connection)36 Session (com.trilead.ssh2.Session)34 IOException (java.io.IOException)31 InputStream (java.io.InputStream)22 SCPClient (com.trilead.ssh2.SCPClient)15 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 ConfigurationException (javax.naming.ConfigurationException)6 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 File (java.io.File)4 Principal (java.security.Principal)4 HashMap (java.util.HashMap)4 Connection (okhttp3.Connection)4 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)4 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 Charset (java.nio.charset.Charset)3 TimeoutException (java.util.concurrent.TimeoutException)3