Search in sources :

Example 6 with SFTPClient

use of org.glassfish.cluster.ssh.sftp.SFTPClient 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 SFTPClient

use of org.glassfish.cluster.ssh.sftp.SFTPClient in project Payara by payara.

the class LogFilterForInstance method downloadAllInstanceLogFiles.

public void downloadAllInstanceLogFiles(ServiceLocator habitat, Server targetServer, Domain domain, Logger logger, String instanceName, String tempDirectoryOnServer, String instanceLogFileDirectory) throws IOException {
    // method is used from collect-log-files command
    // for Instance it's going through this loop. This will use ssh utility to get file from instance machine(remote machine) and
    // store in  tempDirectoryOnServer which is used to create zip file.
    // Right now user needs to go through this URL to setup and configure ssh http://wikis.sun.com/display/GlassFish/3.1SSHSetup
    SSHLauncher sshL = getSSHL(habitat);
    String sNode = targetServer.getNodeRef();
    Nodes nodes = domain.getNodes();
    Node node = nodes.getNode(sNode);
    if (node.getType().equals("SSH")) {
        sshL.init(node, logger);
        List<String> allInstanceLogFileName = getInstanceLogFileNames(habitat, targetServer, domain, logger, instanceName, instanceLogFileDirectory);
        boolean noFileFound = true;
        String sourceDir = getLoggingDirectoryForNode(instanceLogFileDirectory, node, sNode, instanceName);
        SFTPClient sftpClient = sshL.getSFTPClient();
        try {
            List instanceLogFileNames = sftpClient.ls(sourceDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    noFileFound = false;
                    break;
                }
            }
        } catch (Exception e) {
            // if directory doesn't present or missing on remote machine. It happens due to bug 16451
            noFileFound = true;
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            sourceDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileDirectory, node, sNode, instanceName);
        }
        String[] remoteFileNames = new String[allInstanceLogFileName.size()];
        for (int i = 0; i < allInstanceLogFileName.size(); i++) {
            remoteFileNames[i] = sourceDir + File.separator + allInstanceLogFileName.get(i);
        }
        sftpClient.close();
        SCPClient scpClient = sshL.getSCPClient();
        scpClient.get(remoteFileNames, tempDirectoryOnServer);
    } else if (node.getType().equals("DCOM")) {
        List instanceLogFileNames = getInstanceLogFileNames(habitat, targetServer, domain, logger, instanceName, instanceLogFileDirectory);
        String sourceDir = getLoggingDirectoryForNode(instanceLogFileDirectory, node, sNode, instanceName);
        try {
            DcomInfo info = new DcomInfo(node);
            WindowsRemoteFileSystem wrfs = new WindowsRemoteFileSystem(info.getHost(), info.getUser(), info.getPassword());
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                String logFileName = (String) instanceLogFileNames.get(i);
                WindowsRemoteFile wrf = new WindowsRemoteFile(wrfs, sourceDir + File.separator + logFileName);
                File instanceLogFile = new File(tempDirectoryOnServer + File.separator + logFileName);
                wrf.copyTo(instanceLogFile);
            }
        } catch (WindowsException ex) {
            throw new IOException("Unable to download instance log file from DCOM Instance Node");
        }
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) Node(com.sun.enterprise.config.serverbeans.Node) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) Nodes(com.sun.enterprise.config.serverbeans.Nodes) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) DcomInfo(org.glassfish.cluster.ssh.util.DcomInfo) SFTPv3DirectoryEntry(com.trilead.ssh2.SFTPv3DirectoryEntry) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) WindowsRemoteFileSystem(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem) ArrayList(java.util.ArrayList) List(java.util.List) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile)

Example 8 with SFTPClient

use of org.glassfish.cluster.ssh.sftp.SFTPClient in project Payara by payara.

the class LogFilterForInstance method getInstanceLogFileNames.

public List<String> getInstanceLogFileNames(ServiceLocator habitat, Server targetServer, Domain domain, Logger logger, String instanceName, String instanceLogFileDetails) throws IOException {
    // helper method to get all log file names for given instance
    String sNode = targetServer.getNodeRef();
    Node node = domain.getNodes().getNode(sNode);
    List instanceLogFileNames = null;
    List<String> instanceLogFileNamesAsString = new ArrayList();
    // this code is used when DAS and instances are running on the same machine
    if (node.isLocal()) {
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        File logsDir = new File(loggingDir);
        File[] allLogFileNames = logsDir.listFiles();
        boolean noFileFound = true;
        if (allLogFileNames != null) {
            // This check for,  if directory doesn't present or missing on machine. It happens due to bug 16451
            for (File file : allLogFileNames) {
                String fileName = file.getName();
                // code to remove . and .. file which is return
                if (file.isFile() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                    noFileFound = false;
                }
            }
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            loggingDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileDetails, node, sNode, instanceName);
            logsDir = new File(loggingDir);
            allLogFileNames = logsDir.listFiles();
            for (File file : allLogFileNames) {
                String fileName = file.getName();
                // code to remove . and .. file which is return
                if (file.isFile() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                }
            }
        }
    } else if (node.getType().equals("SSH")) {
        // this code is used if DAS and instance are running on different machine
        SSHLauncher sshL = getSSHL(habitat);
        sshL.init(node, logger);
        SFTPClient sftpClient = sshL.getSFTPClient();
        boolean noFileFound = true;
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        try {
            instanceLogFileNames = sftpClient.ls(loggingDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                    noFileFound = false;
                }
            }
        } catch (Exception ex) {
            // if directory doesn't present or missing on remote machine. It happens due to bug 16451
            noFileFound = true;
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            loggingDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileDetails, node, sNode, instanceName);
            instanceLogFileNames = sftpClient.ls(loggingDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                }
            }
        }
        sftpClient.close();
    } else if (node.getType().equals("DCOM")) {
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        try {
            DcomInfo info = new DcomInfo(node);
            WindowsRemoteFileSystem wrfs = new WindowsRemoteFileSystem(info.getHost(), info.getUser(), info.getPassword());
            WindowsRemoteFile wrf = new WindowsRemoteFile(wrfs, loggingDir);
            String[] allLogFileNames = wrf.list();
            for (int i = 0; i < allLogFileNames.length; i++) {
                File file = new File(allLogFileNames[i]);
                String fileName = file.getName();
                // code to remove . and .. file which is return
                if (!fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                }
            }
        } catch (WindowsException ex) {
            throw new IOException("Unable to get instance log file names from DCOM Instance Node");
        }
    }
    return instanceLogFileNamesAsString;
}
Also used : SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) Node(com.sun.enterprise.config.serverbeans.Node) ArrayList(java.util.ArrayList) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) DcomInfo(org.glassfish.cluster.ssh.util.DcomInfo) SFTPv3DirectoryEntry(com.trilead.ssh2.SFTPv3DirectoryEntry) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) WindowsRemoteFileSystem(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem) ArrayList(java.util.ArrayList) List(java.util.List) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile)

Example 9 with SFTPClient

use of org.glassfish.cluster.ssh.sftp.SFTPClient in project Payara by payara.

the class SSHLauncher method validate.

/* validate user provided ars
     *          check connecton to host
     *          check that the install dir is correct
     *          landmarkPath must be relative to the installdir
     */
public void validate(String host, int port, String userName, String password, String keyFile, String keyPassPhrase, String installDir, String landmarkPath, Logger logger) throws IOException {
    boolean validInstallDir = false;
    init(userName, host, port, password, keyFile, keyPassPhrase, logger);
    openConnection();
    logger.fine("Connection settings valid");
    String testPath = installDir;
    if (StringUtils.ok(testPath)) {
        // Validate if installDir exists
        SFTPClient sftpClient = new SFTPClient(connection);
        if (sftpClient.exists(testPath)) {
            // installDir exists. Now check for landmark if provided
            if (StringUtils.ok(landmarkPath)) {
                testPath = installDir + "/" + landmarkPath;
            }
            validInstallDir = sftpClient.exists(testPath);
        } else {
            validInstallDir = false;
        }
        SSHUtil.unregister(connection);
        connection = null;
        if (!validInstallDir) {
            String msg = "Invalid install directory: could not find " + testPath + " on " + host;
            throw new FileNotFoundException(msg);
        }
        logger.fine("Node home validated");
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient)

Aggregations

SFTPClient (org.glassfish.cluster.ssh.sftp.SFTPClient)9 Node (com.sun.enterprise.config.serverbeans.Node)3 WindowsRemoteFile (com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile)3 WindowsRemoteFileSystem (com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem)3 WindowsException (com.sun.enterprise.util.cluster.windows.process.WindowsException)3 SCPClient (com.trilead.ssh2.SCPClient)3 SFTPv3DirectoryEntry (com.trilead.ssh2.SFTPv3DirectoryEntry)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 CommandException (org.glassfish.api.admin.CommandException)3 SSHLauncher (org.glassfish.cluster.ssh.launcher.SSHLauncher)3 DcomInfo (org.glassfish.cluster.ssh.util.DcomInfo)3 Nodes (com.sun.enterprise.config.serverbeans.Nodes)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 ProcessManagerException (com.sun.enterprise.universal.process.ProcessManagerException)1 Connection (com.trilead.ssh2.Connection)1 SFTPv3FileAttributes (com.trilead.ssh2.SFTPv3FileAttributes)1 File (java.io.File)1