Search in sources :

Example 41 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 42 with Connection

use of com.trilead.ssh2.Connection 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 43 with Connection

use of com.trilead.ssh2.Connection in project warn-report by saaavsaaa.

the class LinuxExecUtil method connect.

public Connection connect(String host, String user, String password, String keyPath) throws IOException {
    conn = new Connection(host);
    conn.connect();
    File KeyFile = new File(keyPath);
    boolean isAuthenticated = conn.authenticateWithPublicKey(user, KeyFile, password);
    if (isAuthenticated == false) {
        throw new IOException("Authentication failed.");
    }
    return conn;
}
Also used : Connection(ch.ethz.ssh2.Connection)

Example 44 with Connection

use of com.trilead.ssh2.Connection in project WeexErosFramework by bmfe.

the class WeexOkhttp3Interceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());
    Request request = chain.request();
    mEventReporter = NetworkEventReporterManager.get();
    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter != null) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper);
        mEventReporter.requestWillBeSent(inspectorRequest);
    }
    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter != null) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }
    if (mEventReporter != null) {
        if (requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }
        Connection connection = chain.connection();
        mEventReporter.responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response));
        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }
        responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }
    return response;
}
Also used : InputStream(java.io.InputStream) Request(okhttp3.Request) Connection(okhttp3.Connection) IOException(java.io.IOException) DefaultResponseHandler(com.taobao.weex.devtools.inspector.network.DefaultResponseHandler) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) RequestBodyHelper(com.taobao.weex.devtools.inspector.network.RequestBodyHelper) MediaType(okhttp3.MediaType)

Example 45 with Connection

use of com.trilead.ssh2.Connection 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)

Aggregations

Connection (com.trilead.ssh2.Connection)40 IOException (java.io.IOException)37 Session (com.trilead.ssh2.Session)36 InputStream (java.io.InputStream)23 SCPClient (com.trilead.ssh2.SCPClient)16 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 File (java.io.File)7 Connection (okhttp3.Connection)6 Request (okhttp3.Request)6 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 ConfigurationException (javax.naming.ConfigurationException)5 MediaType (okhttp3.MediaType)5 RequestBody (okhttp3.RequestBody)5 Response (okhttp3.Response)5 ResponseBody (okhttp3.ResponseBody)5 Connection (ch.ethz.ssh2.Connection)4 Charset (java.nio.charset.Charset)4