Search in sources :

Example 6 with JSchException

use of com.jcraft.jsch.JSchException in project camel by apache.

the class SftpOperations method createSession.

protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException {
    final JSch jsch = new JSch();
    JSch.setLogger(new JSchLogger(endpoint.getConfiguration().getJschLoggingLevel()));
    SftpConfiguration sftpConfig = (SftpConfiguration) configuration;
    if (isNotEmpty(sftpConfig.getCiphers())) {
        LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
        Hashtable<String, String> ciphers = new Hashtable<String, String>();
        ciphers.put("cipher.s2c", sftpConfig.getCiphers());
        ciphers.put("cipher.c2s", sftpConfig.getCiphers());
        JSch.setConfig(ciphers);
    }
    if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
        LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
        } else {
            jsch.addIdentity(sftpConfig.getPrivateKeyFile());
        }
    }
    if (sftpConfig.getPrivateKey() != null) {
        LOG.debug("Using private key information from byte array");
        byte[] passphrase = null;
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            try {
                passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new JSchException("Cannot transform passphrase to byte[]", e);
            }
        }
        jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
    }
    if (sftpConfig.getPrivateKeyUri() != null) {
        LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
        byte[] passphrase = null;
        if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
            try {
                passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new JSchException("Cannot transform passphrase to byte[]", e);
            }
        }
        try {
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getPrivateKeyUri());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOHelper.copyAndCloseInput(is, bos);
            jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
        } catch (IOException e) {
            throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
        }
    }
    if (sftpConfig.getKeyPair() != null) {
        LOG.debug("Using private key information from key pair");
        KeyPair keyPair = sftpConfig.getKeyPair();
        if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
            if (keyPair.getPrivate() instanceof RSAPrivateKey && keyPair.getPublic() instanceof RSAPublicKey) {
                jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
            } else if (keyPair.getPrivate() instanceof DSAPrivateKey && keyPair.getPublic() instanceof DSAPublicKey) {
                jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
            } else {
                LOG.warn("Only RSA and DSA key pairs are supported");
            }
        } else {
            LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
        }
    }
    if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
        LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
        jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
    }
    if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
        LOG.debug("Using known hosts uri: {}", sftpConfig.getKnownHostsUri());
        try {
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getKnownHostsUri());
            jsch.setKnownHosts(is);
        } catch (IOException e) {
            throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
        }
    }
    if (sftpConfig.getKnownHosts() != null) {
        LOG.debug("Using known hosts information from byte array");
        jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
    }
    String knownHostsFile = sftpConfig.getKnownHostsFile();
    if (knownHostsFile == null && sftpConfig.isUseUserKnownHostsFile()) {
        knownHostsFile = System.getProperty("user.home") + "/.ssh/known_hosts";
        LOG.info("Known host file not configured, using user known host file: {}", knownHostsFile);
    }
    if (ObjectHelper.isNotEmpty(knownHostsFile)) {
        LOG.debug("Using known hosts information from file: {}", knownHostsFile);
        jsch.setKnownHosts(knownHostsFile);
    }
    final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());
    if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
        LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
        session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
    }
    session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
    session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());
    // compression
    if (sftpConfig.getCompression() > 0) {
        LOG.debug("Using compression: {}", sftpConfig.getCompression());
        session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
        session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
        session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
    }
    // set the PreferredAuthentications 
    if (sftpConfig.getPreferredAuthentications() != null) {
        LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
        session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
    }
    // set user information
    session.setUserInfo(new ExtendedUserInfo() {

        public String getPassphrase() {
            return null;
        }

        public String getPassword() {
            return configuration.getPassword();
        }

        public boolean promptPassword(String s) {
            return true;
        }

        public boolean promptPassphrase(String s) {
            return true;
        }

        public boolean promptYesNo(String s) {
            LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
            // Return 'false' indicating modification of the hosts file is disabled.
            return false;
        }

        public void showMessage(String s) {
            LOG.trace("Message received from Server: " + s);
        }

        public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
            // must return an empty array if password is null
            if (configuration.getPassword() == null) {
                return new String[0];
            } else {
                return new String[] { configuration.getPassword() };
            }
        }
    });
    // set the SO_TIMEOUT for the time after the connect phase
    if (configuration.getSoTimeout() > 0) {
        session.setTimeout(configuration.getSoTimeout());
    }
    // set proxy if configured
    if (proxy != null) {
        session.setProxy(proxy);
    }
    return session;
}
Also used : JSchException(com.jcraft.jsch.JSchException) KeyPair(java.security.KeyPair) Hashtable(java.util.Hashtable) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) DSAPublicKey(java.security.interfaces.DSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Session(com.jcraft.jsch.Session)

Example 7 with JSchException

use of com.jcraft.jsch.JSchException in project che by eclipse.

the class SshManager method generatePair.

/**
     * Generates and stores ssh pair for specified user.
     *
     * @param owner
     *         the id of the user who will be the owner of the ssh pair
     * @param service
     *         service name pf ssh pair
     * @param name
     *         name of pair
     * @return instance of generated ssh pair
     * @throws ConflictException
     *         when given ssh pair cannot be generated or created
     * @throws ServerException
     *         when any other error occurs during ssh pair generating or creating
     */
public SshPairImpl generatePair(String owner, String service, String name) throws ServerException, ConflictException {
    KeyPair keyPair;
    try {
        keyPair = KeyPair.genKeyPair(genJSch, 2, 2048);
    } catch (JSchException e) {
        throw new ServerException("Failed to generate ssh pair.", e);
    }
    ByteArrayOutputStream privateBuff = new ByteArrayOutputStream();
    keyPair.writePrivateKey(privateBuff);
    ByteArrayOutputStream publicBuff = new ByteArrayOutputStream();
    keyPair.writePublicKey(publicBuff, null);
    final SshPairImpl generatedSshPair = new SshPairImpl(owner, service, name, publicBuff.toString(), privateBuff.toString());
    sshDao.create(generatedSshPair);
    return generatedSshPair;
}
Also used : JSchException(com.jcraft.jsch.JSchException) KeyPair(com.jcraft.jsch.KeyPair) ServerException(org.eclipse.che.api.core.ServerException) SshPairImpl(org.eclipse.che.api.ssh.server.model.impl.SshPairImpl) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 8 with JSchException

use of com.jcraft.jsch.JSchException in project DataX by alibaba.

the class SftpHelperImpl method loginFtpServer.

@Override
public void loginFtpServer(String host, String username, String password, int port, int timeout) {
    JSch jsch = new JSch();
    try {
        this.session = jsch.getSession(username, host, port);
        if (this.session == null) {
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, "创建ftp连接this.session失败,无法通过sftp与服务器建立链接,请检查主机名和用户名是否正确.");
        }
        this.session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // config.put("PreferredAuthentications", "password");
        this.session.setConfig(config);
        this.session.setTimeout(timeout);
        this.session.connect();
        this.channelSftp = (ChannelSftp) this.session.openChannel("sftp");
        this.channelSftp.connect();
    } catch (JSchException e) {
        if (null != e.getCause()) {
            String cause = e.getCause().toString();
            String unknownHostException = "java.net.UnknownHostException: " + host;
            String illegalArgumentException = "java.lang.IllegalArgumentException: port out of range:" + port;
            String wrongPort = "java.net.ConnectException: Connection refused";
            if (unknownHostException.equals(cause)) {
                String message = String.format("请确认ftp服务器地址是否正确,无法连接到地址为: [%s] 的ftp服务器, errorMessage:%s", host, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            } else if (illegalArgumentException.equals(cause) || wrongPort.equals(cause)) {
                String message = String.format("请确认连接ftp服务器端口是否正确,错误的端口: [%s], errorMessage:%s", port, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            }
        } else {
            String message = String.format("与ftp服务器建立连接失败,请检查主机、用户名、密码是否正确, host:%s, port:%s, username:%s, errorMessage:%s", host, port, username, e.getMessage());
            LOG.error(message);
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties)

Example 9 with JSchException

use of com.jcraft.jsch.JSchException in project che by eclipse.

the class JschSshClient method start.

@Override
public void start() throws MachineException {
    try {
        session = jsch.getSession(username, host, port);
        session.setUserInfo(user);
        // todo remember parent pid of shell to be able to kill all processes on client stop
        if (!session.isConnected()) {
            session.connect(connectionTimeout);
        }
    } catch (JSchException e) {
        throw new MachineException("Ssh machine creation failed because ssh of machine is inaccessible. Error: " + e.getLocalizedMessage());
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) MachineException(org.eclipse.che.api.machine.server.exception.MachineException)

Example 10 with JSchException

use of com.jcraft.jsch.JSchException in project che by eclipse.

the class JschSshClient method createProcess.

@Override
public JschSshProcess createProcess(String commandLine) throws MachineException {
    try {
        ChannelExec exec = (ChannelExec) session.openChannel("exec");
        exec.setCommand(commandLine);
        exec.setPty(true);
        envVars.entrySet().stream().forEach(envVariableEntry -> exec.setEnv(envVariableEntry.getKey(), envVariableEntry.getValue()));
        return new JschSshProcess(exec);
    } catch (JSchException e) {
        throw new MachineException("Can't establish connection to perform command execution in ssh machine. Error: " + e.getLocalizedMessage(), e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) ChannelExec(com.jcraft.jsch.ChannelExec)

Aggregations

JSchException (com.jcraft.jsch.JSchException)52 IOException (java.io.IOException)25 Session (com.jcraft.jsch.Session)20 JSch (com.jcraft.jsch.JSch)15 Channel (com.jcraft.jsch.Channel)11 ChannelSftp (com.jcraft.jsch.ChannelSftp)11 ChannelExec (com.jcraft.jsch.ChannelExec)9 SftpException (com.jcraft.jsch.SftpException)9 InputStream (java.io.InputStream)7 ArrayList (java.util.ArrayList)7 UserInfo (com.jcraft.jsch.UserInfo)6 File (java.io.File)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 OutputStream (java.io.OutputStream)5 Properties (java.util.Properties)5 MachineException (org.eclipse.che.api.machine.server.exception.MachineException)5 SSHShell (com.microsoft.azure.management.samples.SSHShell)4 FileInputStream (java.io.FileInputStream)4 IStatus (org.eclipse.core.runtime.IStatus)4 Status (org.eclipse.core.runtime.Status)4