Search in sources :

Example 46 with Connection

use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.

the class UsingKnownHosts method main.

public static void main(String[] args) throws IOException {
    String hostname = "somehost";
    String username = "joe";
    String password = "joespass";
    File knownHosts = new File("~/.ssh/known_hosts");
    try {
        if (knownHosts.exists())
            database.addHostkeys(knownHosts);
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* Now connect and use the SimpleVerifier */
        conn.connect(new SimpleVerifier(database));
        /* Authenticate */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("uname -a && date && uptime && who");
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        System.out.println("Here is some information about the remote host:");
        while (true) {
            String line = br.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) Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 47 with Connection

use of org.openmuc.j62056.Connection in project wildfly by wildfly.

the class ServerSecurityInterceptor method aroundInvoke.

@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
    Principal desiredUser = null;
    RealmUser connectionUser = null;
    Map<String, Object> contextData = invocationContext.getContextData();
    if (contextData.containsKey(DELEGATED_USER_KEY)) {
        desiredUser = new SimplePrincipal((String) contextData.get(DELEGATED_USER_KEY));
        Connection con = RemotingContext.getConnection();
        if (con != null) {
            SecurityIdentity localIdentity = con.getLocalIdentity();
            if (localIdentity != null) {
                connectionUser = new RealmUser(localIdentity.getPrincipal().getName());
            }
        } else {
            throw new IllegalStateException("Delegation user requested but no user on connection found.");
        }
    }
    SecurityContext cachedSecurityContext = null;
    boolean contextSet = false;
    try {
        if (desiredUser != null && connectionUser != null && (desiredUser.getName().equals(connectionUser.getName()) == false)) {
            try {
                // The final part of this check is to verify that the change does actually indicate a change in user.
                // We have been requested to switch user and have successfully identified the user from the connection
                // so now we attempt the switch.
                cachedSecurityContext = SecurityContextAssociation.getSecurityContext();
                final SecurityContext nextContext = SecurityContextFactory.createSecurityContext(desiredUser, new CurrentUserCredential(connectionUser.getName()), new Subject(), "fooSecurityDomain");
                SecurityContextAssociation.setSecurityContext(nextContext);
                // keep track that we switched the security context
                contextSet = true;
                RemotingContext.clear();
            } catch (Exception e) {
                LOGGER.error("Failed to switch security context for user", e);
                // Don't propagate the exception stacktrace back to the client for security reasons
                throw new EJBAccessException("Unable to attempt switching of user.");
            }
        }
        return invocationContext.proceed();
    } finally {
        // switch back to original security context
        if (contextSet) {
            SecurityContextAssociation.setSecurityContext(cachedSecurityContext);
        }
    }
}
Also used : IllegalStateException(javax.resource.spi.IllegalStateException) RealmUser(org.jboss.as.core.security.RealmUser) Connection(org.jboss.remoting3.Connection) Subject(javax.security.auth.Subject) EJBAccessException(javax.ejb.EJBAccessException) IllegalStateException(javax.resource.spi.IllegalStateException) EJBAccessException(javax.ejb.EJBAccessException) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SecurityContext(org.jboss.security.SecurityContext) Principal(java.security.Principal) SimplePrincipal(org.jboss.security.SimplePrincipal) SimplePrincipal(org.jboss.security.SimplePrincipal) AroundInvoke(javax.interceptor.AroundInvoke)

Example 48 with Connection

use of org.openmuc.j62056.Connection in project ACS by ACS-Community.

the class Executor method remoteDownAllPortable.

/**
	 * Shuts down all ssh-sessions and -connections that may still be active.
	 */
private static void remoteDownAllPortable() {
    for (Session sess : sessions) {
        try {
            sess.close();
            log.fine("closed " + sess);
        } catch (Exception exc) {
            log.fine("could not close " + sess);
        }
    }
    for (Connection conn : connections) {
        try {
            conn.close();
            log.fine("closed " + conn);
        } catch (Exception exc) {
            log.fine("could not close " + conn);
        }
    }
}
Also used : Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) OrbInitException(alma.acs.commandcenter.meta.Firestarter.OrbInitException) AcsJException(alma.acs.exceptions.AcsJException) Session(com.trilead.ssh2.Session)

Example 49 with Connection

use of org.openmuc.j62056.Connection in project cloudstack by apache.

the class StressTestDirectAttach 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 " + 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 (// 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) {
                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();
            }
        }
    }
}
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)

Example 50 with Connection

use of org.openmuc.j62056.Connection in project cloudstack by apache.

the class EventsApiTest 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;
        //!!!check if we need to execute mySql command
        NodeList commandName = fstElmnt.getElementsByTagName("name");
        Element commandElmnt = (Element) commandName.item(0);
        NodeList commandNm = commandElmnt.getChildNodes();
        if (commandNm.item(0).getNodeValue().equals("mysqlupdate")) {
            //establish connection to mysql server and execute an update command
            NodeList mysqlList = fstElmnt.getElementsByTagName("mysqlcommand");
            for (int j = 0; j < mysqlList.getLength(); j++) {
                Element itemVariableElement = (Element) mysqlList.item(j);
                s_logger.info("Executing mysql command " + itemVariableElement.getTextContent());
                try {
                    Statement st = this.getConn().createStatement();
                    st.executeUpdate(itemVariableElement.getTextContent());
                } catch (Exception ex) {
                    s_logger.error(ex);
                    return false;
                }
            }
        } else if (commandNm.item(0).getNodeValue().equals("agentcommand")) {
            //connect to all the agents and execute agent command
            NodeList commandList = fstElmnt.getElementsByTagName("commandname");
            Element commandElement = (Element) commandList.item(0);
            NodeList ipList = fstElmnt.getElementsByTagName("ip");
            for (int j = 0; j < ipList.getLength(); j++) {
                Element itemVariableElement = (Element) ipList.item(j);
                s_logger.info("Attempting to SSH into agent " + itemVariableElement.getTextContent());
                try {
                    Connection conn = new Connection(itemVariableElement.getTextContent());
                    conn.connect(null, 60000, 60000);
                    s_logger.info("SSHed successfully into agent " + itemVariableElement.getTextContent());
                    boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
                    if (isAuthenticated == false) {
                        s_logger.info("Authentication failed for root with password");
                        return false;
                    }
                    Session sess = conn.openSession();
                    s_logger.info("Executing : " + commandElement.getTextContent());
                    sess.execCommand(commandElement.getTextContent());
                    Thread.sleep(60000);
                    sess.close();
                    conn.close();
                } catch (Exception ex) {
                    s_logger.error(ex);
                    return false;
                }
            }
        } else {
            //new command
            ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
            //send a command
            api.sendCommand(this.getClient(), null);
            //verify the response of the command
            if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200)) {
                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)) {
                //verify if response is suppposed to be empty
                if (api.getResponseType() == ResponseType.EMPTY) {
                    if (api.isEmpty() == true) {
                        s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Empty response was returned as expected. Command was sent with url " + api.getUrl());
                    } else {
                        s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Empty response was expected. Command was sent with url " + api.getUrl());
                    }
                } else {
                    if (api.isEmpty() != false)
                        s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Non-empty response was expected. Command was sent with url " + api.getUrl());
                    else {
                        //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 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());
                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. Command was sent with url " + api.getUrl());
            }
        }
    }
    //verify events with userid parameter - test case 97
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    expectedEvents.put("VM.START", 1);
    boolean eventResult = ApiCommand.verifyEvents(expectedEvents, "INFO", "http://" + this.getParam().get("hostip") + ":8096", "userid=" + this.getParam().get("userid1") + "&type=VM.START");
    s_logger.info("Test case 97 - listEvent command verification result is  " + eventResult);
    //verify error events
    eventResult = ApiCommand.verifyEvents("../metadata/error_events.properties", "ERROR", "http://" + this.getParam().get("hostip") + ":8096", this.getParam().get("erroruseraccount"));
    s_logger.info("listEvent command verification result is  " + eventResult);
    if (error != 0)
        return false;
    else
        return true;
}
Also used : HashMap(java.util.HashMap) Statement(java.sql.Statement) 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)

Aggregations

Connection (com.trilead.ssh2.Connection)40 Session (com.trilead.ssh2.Session)31 IOException (java.io.IOException)29 InputStream (java.io.InputStream)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 SCPClient (com.trilead.ssh2.SCPClient)7 Connection (okhttp3.Connection)6 Request (okhttp3.Request)6 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 MediaType (okhttp3.MediaType)5 RequestBody (okhttp3.RequestBody)5 Response (okhttp3.Response)5 ResponseBody (okhttp3.ResponseBody)5 Connection (ch.ethz.ssh2.Connection)4 File (java.io.File)4 Charset (java.nio.charset.Charset)4 Principal (java.security.Principal)4