Search in sources :

Example 21 with Session

use of com.jcraft.jsch.Session 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 22 with Session

use of com.jcraft.jsch.Session in project hadoop by apache.

the class SshFenceByTcpPort method tryFence.

@Override
public boolean tryFence(HAServiceTarget target, String argsStr) throws BadFencingConfigurationException {
    Args args = new Args(argsStr);
    InetSocketAddress serviceAddr = target.getAddress();
    String host = serviceAddr.getHostName();
    Session session;
    try {
        session = createSession(serviceAddr.getHostName(), args);
    } catch (JSchException e) {
        LOG.warn("Unable to create SSH session", e);
        return false;
    }
    LOG.info("Connecting to " + host + "...");
    try {
        session.connect(getSshConnectTimeout());
    } catch (JSchException e) {
        LOG.warn("Unable to connect to " + host + " as user " + args.user, e);
        return false;
    }
    LOG.info("Connected to " + host);
    try {
        return doFence(session, serviceAddr);
    } catch (JSchException e) {
        LOG.warn("Unable to achieve fencing on remote host", e);
        return false;
    } finally {
        session.disconnect();
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) InetSocketAddress(java.net.InetSocketAddress) Session(com.jcraft.jsch.Session)

Example 23 with Session

use of com.jcraft.jsch.Session in project hadoop by apache.

the class SFTPConnectionPool method disconnect.

void disconnect(ChannelSftp channel) throws IOException {
    if (channel != null) {
        // close connection if too many active connections
        boolean closeConnection = false;
        synchronized (this) {
            if (liveConnectionCount > maxConnection) {
                --liveConnectionCount;
                con2infoMap.remove(channel);
                closeConnection = true;
            }
        }
        if (closeConnection) {
            if (channel.isConnected()) {
                try {
                    Session session = channel.getSession();
                    channel.disconnect();
                    session.disconnect();
                } catch (JSchException e) {
                    throw new IOException(StringUtils.stringifyException(e));
                }
            }
        } else {
            returnToPool(channel);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) IOException(java.io.IOException) Session(com.jcraft.jsch.Session)

Example 24 with Session

use of com.jcraft.jsch.Session 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)

Example 25 with Session

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

the class TestVirtualMachineCustomData method createResource.

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16);
    // Prepare the custom data
    //
    String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath();
    // In Windows remove leading slash
    cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1");
    byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath));
    byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes);
    String cloudInitEncodedString = new String(cloudInitEncoded);
    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_16_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
    pip.refresh();
    Assert.assertTrue(pip.hasAssignedNetworkInterface());
    if (!MockIntegrationTestBase.IS_MOCKED) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelExec channel = null;
        try {
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
            session.setPassword("12NewPA$$w0rd!");
            session.setConfig(config);
            session.connect();
            // Try running the package installed via init script
            //
            channel = (ChannelExec) session.openChannel("exec");
            BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            channel.setCommand("pwgen;");
            channel.connect();
            String msg;
            while ((msg = in.readLine()) != null) {
                Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed"));
            }
        } catch (Exception e) {
            Assert.fail("SSH connection failed" + e.getMessage());
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
    return vm;
}
Also used : InputStreamReader(java.io.InputStreamReader) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) JSch(com.jcraft.jsch.JSch) ChannelExec(com.jcraft.jsch.ChannelExec) BufferedReader(java.io.BufferedReader) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine) Session(com.jcraft.jsch.Session)

Aggregations

Session (com.jcraft.jsch.Session)41 JSch (com.jcraft.jsch.JSch)23 JSchException (com.jcraft.jsch.JSchException)20 IOException (java.io.IOException)16 Channel (com.jcraft.jsch.Channel)13 ChannelSftp (com.jcraft.jsch.ChannelSftp)11 File (java.io.File)9 ChannelExec (com.jcraft.jsch.ChannelExec)7 SftpException (com.jcraft.jsch.SftpException)7 InputStream (java.io.InputStream)7 FileInputStream (java.io.FileInputStream)6 UserInfo (com.jcraft.jsch.UserInfo)5 OutputStream (java.io.OutputStream)5 EditableDockerHost (com.microsoft.azure.docker.model.EditableDockerHost)4 DockerHost (com.microsoft.azure.docker.model.DockerHost)3 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)3 AzureDockerPreferredSettings (com.microsoft.azure.docker.model.AzureDockerPreferredSettings)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 AzureInputDockerLoginCredsDialog (com.microsoft.azuretools.docker.ui.dialogs.AzureInputDockerLoginCredsDialog)2 AzureInputDockerLoginCredsDialog (com.microsoft.intellij.docker.dialogs.AzureInputDockerLoginCredsDialog)2