Search in sources :

Example 71 with JSch

use of com.jcraft.jsch.JSch in project incubator-gobblin by apache.

the class GitMonitoringService method getSshSessionFactory.

private SshSessionFactory getSshSessionFactory() {
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {

        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
            if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            if (GitMonitoringService.this.isJschLoggerEnabled) {
                JSch.setLogger(new JschLogger());
            }
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.getIdentityRepository().removeAll();
            if (GitMonitoringService.this.privateKeyPath != null) {
                defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath, GitMonitoringService.this.passphrase);
            } else {
                defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null, GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
            }
            if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
                defaultJSch.setKnownHosts(new ByteArrayInputStream(GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
            } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
                defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
            }
            return defaultJSch;
        }
    };
    return sessionFactory;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) Session(com.jcraft.jsch.Session)

Example 72 with JSch

use of com.jcraft.jsch.JSch in project mybatis-generator-gui by zouzg.

the class DbUtil method getSSHSession.

public static Session getSSHSession(DatabaseConfig databaseConfig) {
    if (StringUtils.isBlank(databaseConfig.getSshHost()) || StringUtils.isBlank(databaseConfig.getSshPort()) || StringUtils.isBlank(databaseConfig.getSshUser()) || (StringUtils.isBlank(databaseConfig.getPrivateKey()) && StringUtils.isBlank(databaseConfig.getSshPassword()))) {
        return null;
    }
    Session session = null;
    try {
        // Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Integer sshPort = NumberUtils.createInteger(databaseConfig.getSshPort());
        int port = sshPort == null ? 22 : sshPort;
        session = jsch.getSession(databaseConfig.getSshUser(), databaseConfig.getSshHost(), port);
        if (StringUtils.isNotBlank(databaseConfig.getPrivateKey())) {
            // 使用秘钥方式认证
            jsch.addIdentity(databaseConfig.getPrivateKey(), StringUtils.defaultIfBlank(databaseConfig.getPrivateKeyPassword(), null));
        } else {
            session.setPassword(databaseConfig.getSshPassword());
        }
        session.setConfig(config);
    } catch (JSchException e) {
    // Ignore
    }
    return session;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JSchException(com.jcraft.jsch.JSchException) java.util(java.util) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 73 with JSch

use of com.jcraft.jsch.JSch in project navajo by Dexels.

the class SFTPMap method send.

private void send() throws UserException {
    // String SFTPWORKINGDIR = "file/to/transfer";
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    logger.debug("preparing the host information for sftp.");
    InputStream data = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(this.username, this.server, this.remotePort);
        if (this.password != null) {
            session.setPassword(this.password);
        }
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        logger.debug("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        logger.debug("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        if (this.path != null) {
            channelSftp.cd(this.path);
        }
        File f = new File(this.filename);
        data = content.getDataAsStream();
        channelSftp.put(data, f.getName());
        logger.info("File transfered successfully to host.");
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new UserException("SFTP problem", ex);
    } finally {
        if (data != null) {
            try {
                data.close();
            } catch (IOException e) {
            }
        }
        if (channelSftp != null) {
            channelSftp.exit();
        }
        logger.info("sftp Channel exited.");
        if (channel != null) {
            channel.disconnect();
        }
        logger.info("Channel disconnected.");
        if (session != null) {
            session.disconnect();
        }
        logger.info("Host Session disconnected.");
    }
}
Also used : InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) IOException(java.io.IOException) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException) ChannelSftp(com.jcraft.jsch.ChannelSftp) UserException(com.dexels.navajo.script.api.UserException) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 74 with JSch

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

the class JGitConnection method executeRemoteCommand.

/**
     * Execute remote jgit command.
     *
     * @param remoteUrl
     *         remote url
     * @param command
     *         command to execute
     * @return executed command
     * @throws GitException
     * @throws GitAPIException
     * @throws UnauthorizedException
     */
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
    File keyDirectory = null;
    UserCredential credentials = null;
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            keyDirectory = Files.createTempDir();
            final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(transport -> {
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
                username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
                password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            } else {
                if (username != null && password != null) {
                    command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
                } else {
                    credentials = credentialsLoader.getUserCredential(remoteUrl);
                    if (credentials != null) {
                        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
                    }
                }
            }
        }
        ProxyAuthenticator.initAuthenticator(remoteUrl);
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())) {
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
        } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
            if (info != null) {
                throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
            }
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
        } else {
            throw exception;
        }
    } finally {
        if (keyDirectory != null && keyDirectory.exists()) {
            try {
                FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
        ProxyAuthenticator.resetAuthenticator();
    }
}
Also used : UserCredential(org.eclipse.che.api.git.UserCredential) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportException(org.eclipse.jgit.api.errors.TransportException) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 75 with JSch

use of com.jcraft.jsch.JSch in project azure-sdk-for-java by Azure.

the class TestVirtualMachineSsh method createResource.

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
    final String publicIpDnsLabel = vmName;
    PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup().withLeafDomainLabel(publicIpDnsLabel).create();
    VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName()).withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
    pip.refresh();
    Assert.assertTrue(pip.hasAssignedNetworkInterface());
    JSch jsch = new JSch();
    Session session = null;
    if (!MockIntegrationTestBase.IS_MOCKED) {
        try {
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            // jsch.addIdentity(sshFile, filePassword);
            session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
            session.setPassword("12NewPA$$w0rd!");
            session.setConfig(config);
            session.connect();
        } catch (Exception e) {
            Assert.fail("SSH connection failed" + e.getMessage());
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }
        Assert.assertNotNull(vm.inner().osProfile().linuxConfiguration().ssh());
        Assert.assertTrue(vm.inner().osProfile().linuxConfiguration().ssh().publicKeys().size() > 0);
    }
    return vm;
}
Also used : PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) JSch(com.jcraft.jsch.JSch) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine) Session(com.jcraft.jsch.Session)

Aggregations

JSch (com.jcraft.jsch.JSch)130 Session (com.jcraft.jsch.Session)72 JSchException (com.jcraft.jsch.JSchException)51 IOException (java.io.IOException)50 Channel (com.jcraft.jsch.Channel)35 File (java.io.File)29 InputStream (java.io.InputStream)29 Properties (java.util.Properties)27 ChannelExec (com.jcraft.jsch.ChannelExec)26 ChannelSftp (com.jcraft.jsch.ChannelSftp)22 KeyPair (com.jcraft.jsch.KeyPair)19 BufferedReader (java.io.BufferedReader)16 UserInfo (com.jcraft.jsch.UserInfo)15 InputStreamReader (java.io.InputStreamReader)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 FileInputStream (java.io.FileInputStream)11 OutputStream (java.io.OutputStream)11 SftpException (com.jcraft.jsch.SftpException)10 FS (org.eclipse.jgit.util.FS)8 FileOutputStream (java.io.FileOutputStream)7