Search in sources :

Example 16 with Connection

use of org.jboss.remoting3.Connection in project cloudstack by apache.

the class SshTest method main.

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = iter.next();
        }
        if (arg.equals("-p")) {
            password = iter.next();
        }
        if (arg.equals("-u")) {
            url = iter.next();
        }
    }
    if (host == null || host.equals("")) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        System.exit(2);
    }
    if (password == null) {
        s_logger.info("Did not receive a password back from test, ignoring ssh test");
        System.exit(2);
    }
    try {
        s_logger.info("Attempting to SSH into host " + host);
        Connection conn = new Connection(host);
        conn.connect(null, 60000, 60000);
        s_logger.info("User + ssHed successfully into host " + host);
        boolean isAuthenticated = conn.authenticateWithPassword("root", password);
        if (isAuthenticated == false) {
            s_logger.info("Authentication failed for root with password" + password);
            System.exit(2);
        }
        String linuxCommand = "wget " + url;
        Session sess = conn.openSession();
        sess.execCommand(linuxCommand);
        sess.close();
        conn.close();
    } catch (Exception e) {
        s_logger.error("SSH test fail with error", e);
        System.exit(2);
    }
}
Also used : Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 17 with Connection

use of org.jboss.remoting3.Connection in project cloudstack by apache.

the class SshHelper method scpTo.

public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, String localFile, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.SCPClient scpClient = 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);
            }
        }
        scpClient = conn.createSCPClient();
        if (fileMode != null)
            scpClient.put(localFile, remoteTargetDirectory, fileMode);
        else
            scpClient.put(localFile, remoteTargetDirectory);
    } finally {
        if (conn != null)
            conn.close();
    }
}
Also used : Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException)

Example 18 with Connection

use of org.jboss.remoting3.Connection in project cloudstack by apache.

the class SshHelper method scpTo.

public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, byte[] data, String remoteFileName, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.SCPClient scpClient = 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);
            }
        }
        scpClient = conn.createSCPClient();
        if (fileMode != null)
            scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode);
        else
            scpClient.put(data, remoteFileName, remoteTargetDirectory);
    } finally {
        if (conn != null)
            conn.close();
    }
}
Also used : Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException)

Example 19 with Connection

use of org.jboss.remoting3.Connection 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)

Example 20 with Connection

use of org.jboss.remoting3.Connection in project cloudstack by apache.

the class SshHelperTest method openConnectionSessionTest.

@Test
public void openConnectionSessionTest() throws IOException, InterruptedException {
    Connection conn = Mockito.mock(Connection.class);
    PowerMockito.mockStatic(Thread.class);
    SshHelper.openConnectionSession(conn);
    Mockito.verify(conn).openSession();
    PowerMockito.verifyStatic();
    Thread.sleep(Mockito.anyLong());
}
Also used : Connection(com.trilead.ssh2.Connection) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Connection (com.trilead.ssh2.Connection)36 Session (com.trilead.ssh2.Session)31 IOException (java.io.IOException)23 InputStream (java.io.InputStream)20 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 Connection (org.jboss.remoting3.Connection)7 SCPClient (com.trilead.ssh2.SCPClient)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 Principal (java.security.Principal)4 Connection (okhttp3.Connection)4 Request (okhttp3.Request)4 RequestBody (okhttp3.RequestBody)4 SecurityContext (org.jboss.security.SecurityContext)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 Headers (okhttp3.Headers)3