Search in sources :

Example 6 with SCPClient

use of com.trilead.ssh2.SCPClient in project Payara by payara.

the class SSHLauncher method setupKey.

/**
 * Setting up the key involves the following steps:
 * -If a key exists and we can connect using the key, do nothing.
 * -Generate a key pair if there isn't one
 * -Connect to remote host using password auth and do the following:
 *  1. create .ssh directory if it doesn't exist
 *  2. copy over the key as key.tmp
 *  3. Append the key to authorized_keys file
 *  4. Remove the temporary key file key.tmp
 *  5. Fix permissions for home, .ssh and authorized_keys
 * @param node        - remote host
 * @param pubKeyFile  - .pub file
 * @param generateKey - flag to indicate if key needs to be generated or not
 * @param passwd      - ssh user password
 * @throws IOException
 * @throws InterruptedException
 */
public void setupKey(String node, String pubKeyFile, boolean generateKey, String passwd) throws IOException, InterruptedException {
    boolean connected = false;
    File key = new File(keyFile);
    if (logger.isLoggable(Level.FINER))
        logger.finer("Key = " + keyFile);
    if (key.exists()) {
        if (checkConnection()) {
            throw new IOException("SSH public key authentication is already configured for " + userName + "@" + node);
        }
    } else {
        if (generateKey) {
            if (!generateKeyPair()) {
                throw new IOException("SSH key pair generation failed. Please generate key manually.");
            }
        } else {
            throw new IOException("SSH key pair not present. Please generate a key pair manually or specify an existing one and re-run the command.");
        }
    }
    // password is must for key distribution
    if (passwd == null) {
        throw new IOException("SSH password is required for distributing the public key. You can specify the SSH password in a password file and pass it through --passwordfile option.");
    }
    connection = new Connection(node, port);
    connection.connect();
    connected = connection.authenticateWithPassword(userName, passwd);
    if (!connected) {
        throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
    }
    // We open up a second connection for scp and exec. For some reason, a hang
    // is seen in MKS if we try to do everything using the same connection.
    Connection conn = new Connection(node, port);
    conn.connect();
    boolean ret = conn.authenticateWithPassword(userName, passwd);
    if (!ret) {
        throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
    }
    // initiate scp client
    SCPClient scp = new SCPClient(conn);
    SFTPClient sftp = new SFTPClient(connection);
    if (key.exists()) {
        // fixes .ssh file mode
        setupSSHDir();
        if (pubKeyFile == null) {
            pubKeyFile = keyFile + ".pub";
        }
        File pubKey = new File(pubKeyFile);
        if (!pubKey.exists()) {
            throw new IOException("Public key file " + pubKeyFile + " does not exist.");
        }
        try {
            if (!sftp.exists(SSH_DIR)) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine(SSH_DIR + " does not exist");
                }
                sftp.mkdirs(".ssh", 0700);
            }
        } catch (Exception e) {
            if (logger.isLoggable(Level.FINER)) {
                e.printStackTrace();
            }
            throw new IOException("Error while creating .ssh directory on remote host:" + e.getMessage());
        }
        // copy over the public key to remote host
        scp.put(pubKey.getAbsolutePath(), "key.tmp", ".ssh", "0600");
        // append the public key file contents to authorized_keys file on remote host
        String mergeCommand = "cd .ssh; cat key.tmp >> " + AUTH_KEY_FILE;
        if (logger.isLoggable(Level.FINER)) {
            logger.finer("mergeCommand = " + mergeCommand);
        }
        if (conn.exec(mergeCommand, new ByteArrayOutputStream()) != 0) {
            throw new IOException("Failed to propogate the public key " + pubKeyFile + " to " + host);
        }
        logger.info("Copied keyfile " + pubKeyFile + " to " + userName + "@" + host);
        // remove the public key file on remote host
        if (conn.exec("rm .ssh/key.tmp", new ByteArrayOutputStream()) != 0) {
            logger.warning("WARNING: Failed to remove the public key file key.tmp on remote host " + host);
        }
        if (logger.isLoggable(Level.FINER)) {
            logger.finer("Removed the temporary key file on remote host");
        }
        // Lets fix all the permissions
        // On MKS, chmod doesn't work as expected. StrictMode needs to be disabled
        // for connection to go through
        logger.info("Fixing file permissions for home(755), .ssh(700) and authorized_keys file(644)");
        sftp.chmod(".", 0755);
        sftp.chmod(SSH_DIR, 0700);
        sftp.chmod(SSH_DIR + AUTH_KEY_FILE, 0644);
        // release the connections
        sftp.close();
        conn.close();
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) Connection(com.trilead.ssh2.Connection) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) IOException(java.io.IOException) File(java.io.File) ProcessManagerException(com.sun.enterprise.universal.process.ProcessManagerException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 7 with SCPClient

use of com.trilead.ssh2.SCPClient in project cosmic by MissionCriticalCloud.

the class SshHelper method scpTo.

public static void scpTo(final String host, final int port, final String user, final File pemKeyFile, final String password, final String remoteTargetDirectory, final String localFile, final String fileMode, final int connectTimeoutInMs, final 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)) {
                final 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)) {
                final 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 8 with SCPClient

use of com.trilead.ssh2.SCPClient in project cosmic by MissionCriticalCloud.

the class SshHelper method scpTo.

public static void scpTo(final String host, final int port, final String user, final File pemKeyFile, final String password, final String remoteTargetDirectory, final byte[] data, final String remoteFileName, final String fileMode, final int connectTimeoutInMs, final 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)) {
                final 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)) {
                final 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 9 with SCPClient

use of com.trilead.ssh2.SCPClient in project cosmic by MissionCriticalCloud.

the class CitrixResourceBase method setupServer.

/* return : if setup is needed */
public boolean setupServer(final Connection conn, final Host host) {
    final String packageVersion = CitrixResourceBase.class.getPackage().getImplementationVersion();
    final String version = this.getClass().getName() + "-" + (packageVersion == null ? Long.toString(System.currentTimeMillis()) : packageVersion);
    try {
        /* push patches to XenServer */
        final Host.Record hr = host.getRecord(conn);
        final Iterator<String> it = hr.tags.iterator();
        while (it.hasNext()) {
            final String tag = it.next();
            if (tag.startsWith("vmops-version-")) {
                if (tag.contains(version)) {
                    s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
                    return false;
                } else {
                    it.remove();
                }
            }
        }
        final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
        try {
            sshConnection.connect(null, 60000, 60000);
            if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                throw new CloudRuntimeException("Unable to authenticate");
            }
            final String cmd = "mkdir -p /opt/cloud/bin /var/log/cloud";
            if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) {
                throw new CloudRuntimeException("Cannot create directory /opt/cloud/bin on XenServer hosts");
            }
            final SCPClient scp = new SCPClient(sshConnection);
            final List<File> files = getPatchFiles();
            if (files == null || files.isEmpty()) {
                throw new CloudRuntimeException("Can not find patch file");
            }
            for (final File file : files) {
                final String path = file.getParentFile().getAbsolutePath() + "/";
                final Properties props = PropertiesUtil.loadFromFile(file);
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    final String k = (String) entry.getKey();
                    final String v = (String) entry.getValue();
                    assert k != null && k.length() > 0 && v != null && v.length() > 0 : "Problems with " + k + "=" + v;
                    final String[] tokens = v.split(",");
                    String f = null;
                    if (tokens.length == 3 && tokens[0].length() > 0) {
                        if (tokens[0].startsWith("/")) {
                            f = tokens[0];
                        } else if (tokens[0].startsWith("~")) {
                            final String homedir = System.getenv("HOME");
                            f = homedir + tokens[0].substring(1) + k;
                        } else {
                            f = path + tokens[0] + '/' + k;
                        }
                    } else {
                        f = path + k;
                    }
                    final String directoryPath = tokens[tokens.length - 1];
                    f = f.replace('/', File.separatorChar);
                    String permissions = "0755";
                    if (tokens.length == 3) {
                        permissions = tokens[1];
                    } else if (tokens.length == 2) {
                        permissions = tokens[0];
                    }
                    if (!new File(f).exists()) {
                        s_logger.warn("We cannot locate " + f);
                        continue;
                    }
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Copying " + f + " to " + directoryPath + " on " + hr.address + " with permission " + permissions);
                    }
                    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "mkdir -m 700 -p " + directoryPath)) {
                        s_logger.debug("Unable to create destination path: " + directoryPath + " on " + hr.address + ".");
                    }
                    try {
                        scp.put(f, directoryPath, permissions);
                    } catch (final IOException e) {
                        final String msg = "Unable to copy file " + f + " to path " + directoryPath + " with permissions  " + permissions;
                        s_logger.debug(msg);
                        throw new CloudRuntimeException("Unable to setup the server: " + msg, e);
                    }
                }
            }
        } catch (final IOException e) {
            throw new CloudRuntimeException("Unable to setup the server correctly", e);
        } finally {
            sshConnection.close();
        }
        hr.tags.add("vmops-version-" + version);
        host.setTags(conn, hr.tags);
        return true;
    } catch (final XenAPIException e) {
        final String msg = "XenServer setup failed due to " + e.toString();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
    } catch (final XmlRpcException e) {
        final String msg = "XenServer setup failed due to " + e.getMessage();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information ", e);
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) Connection(com.xensource.xenapi.Connection) URLConnection(java.net.URLConnection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Host(com.xensource.xenapi.Host) IOException(java.io.IOException) Properties(java.util.Properties) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIObject(com.xensource.xenapi.XenAPIObject) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 10 with SCPClient

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

the class CitrixResourceBase method setupServer.

/* return : if setup is needed */
public boolean setupServer(final Connection conn, final Host host) {
    final String packageVersion = CitrixResourceBase.class.getPackage().getImplementationVersion();
    final String version = this.getClass().getName() + "-" + (packageVersion == null ? Long.toString(System.currentTimeMillis()) : packageVersion);
    try {
        /* push patches to XenServer */
        final Host.Record hr = host.getRecord(conn);
        final Iterator<String> it = hr.tags.iterator();
        while (it.hasNext()) {
            final String tag = it.next();
            if (tag.startsWith("vmops-version-")) {
                if (tag.contains(version)) {
                    s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
                    return false;
                } else {
                    it.remove();
                }
            }
        }
        final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
        try {
            sshConnection.connect(null, 60000, 60000);
            if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                throw new CloudRuntimeException("Unable to authenticate");
            }
            final String cmd = "mkdir -p /opt/cloud/bin /var/log/cloud";
            if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) {
                throw new CloudRuntimeException("Cannot create directory /opt/cloud/bin on XenServer hosts");
            }
            final SCPClient scp = new SCPClient(sshConnection);
            final List<File> files = getPatchFiles();
            if (files == null || files.isEmpty()) {
                throw new CloudRuntimeException("Can not find patch file");
            }
            for (final File file : files) {
                final String path = file.getParentFile().getAbsolutePath() + "/";
                final Properties props = PropertiesUtil.loadFromFile(file);
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    final String k = (String) entry.getKey();
                    final String v = (String) entry.getValue();
                    assert k != null && k.length() > 0 && v != null && v.length() > 0 : "Problems with " + k + "=" + v;
                    final String[] tokens = v.split(",");
                    String f = null;
                    if (tokens.length == 3 && tokens[0].length() > 0) {
                        if (tokens[0].startsWith("/")) {
                            f = tokens[0];
                        } else if (tokens[0].startsWith("~")) {
                            final String homedir = System.getenv("HOME");
                            f = homedir + tokens[0].substring(1) + k;
                        } else {
                            f = path + tokens[0] + '/' + k;
                        }
                    } else {
                        f = path + k;
                    }
                    final String directoryPath = tokens[tokens.length - 1];
                    f = f.replace('/', File.separatorChar);
                    String permissions = "0755";
                    if (tokens.length == 3) {
                        permissions = tokens[1];
                    } else if (tokens.length == 2) {
                        permissions = tokens[0];
                    }
                    if (!new File(f).exists()) {
                        s_logger.warn("We cannot locate " + f);
                        continue;
                    }
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Copying " + f + " to " + directoryPath + " on " + hr.address + " with permission " + permissions);
                    }
                    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "mkdir -m 700 -p " + directoryPath)) {
                        s_logger.debug("Unable to create destination path: " + directoryPath + " on " + hr.address + ".");
                    }
                    try {
                        scp.put(f, directoryPath, permissions);
                    } catch (final IOException e) {
                        final String msg = "Unable to copy file " + f + " to path " + directoryPath + " with permissions  " + permissions;
                        s_logger.debug(msg);
                        throw new CloudRuntimeException("Unable to setup the server: " + msg, e);
                    }
                }
            }
        } catch (final IOException e) {
            throw new CloudRuntimeException("Unable to setup the server correctly", e);
        } finally {
            sshConnection.close();
        }
        hr.tags.add("vmops-version-" + version);
        host.setTags(conn, hr.tags);
        return true;
    } catch (final XenAPIException e) {
        final String msg = "XenServer setup failed due to " + e.toString();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
    } catch (final XmlRpcException e) {
        final String msg = "XenServer setup failed due to " + e.getMessage();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information ", e);
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) Connection(com.xensource.xenapi.Connection) URLConnection(java.net.URLConnection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Host(com.xensource.xenapi.Host) IOException(java.io.IOException) Properties(java.util.Properties) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIObject(com.xensource.xenapi.XenAPIObject) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Aggregations

SCPClient (com.trilead.ssh2.SCPClient)22 IOException (java.io.IOException)15 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)13 Connection (com.trilead.ssh2.Connection)12 ConfigurationException (javax.naming.ConfigurationException)7 Session (com.trilead.ssh2.Session)6 File (java.io.File)6 InputStream (java.io.InputStream)6 Connection (com.xensource.xenapi.Connection)4 XenAPIException (com.xensource.xenapi.Types.XenAPIException)4 URISyntaxException (java.net.URISyntaxException)4 URLConnection (java.net.URLConnection)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 HttpException (org.apache.commons.httpclient.HttpException)4 XmlRpcException (org.apache.xmlrpc.XmlRpcException)4 SFTPClient (org.glassfish.cluster.ssh.sftp.SFTPClient)3 Host (com.xensource.xenapi.Host)2 XenAPIObject (com.xensource.xenapi.XenAPIObject)2 MalformedURLException (java.net.MalformedURLException)2 URI (java.net.URI)2