Search in sources :

Example 21 with JSch

use of com.jcraft.jsch.JSch in project cdap by caskdata.

the class SFTPConnectionPool method connect.

public ChannelSftp connect(String host, int port, String user, String password, String keyFile) throws IOException {
    // get connection from pool
    ConnectionInfo info = new ConnectionInfo(host, port, user);
    ChannelSftp channel = getFromPool(info);
    if (channel != null) {
        if (channel.isConnected()) {
            return channel;
        } else {
            channel = null;
            synchronized (this) {
                --liveConnectionCount;
                con2infoMap.remove(channel);
            }
        }
    }
    // create a new connection and add to pool
    JSch jsch = new JSch();
    Session session = null;
    try {
        if (user == null || user.length() == 0) {
            user = System.getProperty("user.name");
        }
        if (password == null) {
            password = "";
        }
        if (keyFile != null && keyFile.length() > 0) {
            jsch.addIdentity(keyFile);
        }
        if (port <= 0) {
            session = jsch.getSession(user, host);
        } else {
            session = jsch.getSession(user, host, port);
        }
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        synchronized (this) {
            con2infoMap.put(channel, info);
            liveConnectionCount++;
        }
        return channel;
    } catch (JSchException e) {
        throw new IOException(StringUtils.stringifyException(e));
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) ChannelSftp(com.jcraft.jsch.ChannelSftp) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 22 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 23 with JSch

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

the class SftpHelper method loginFtpServer.

@Override
public void loginFtpServer(String host, String username, String password, int port, int timeout, String connectMode) {
    // 创建JSch对象
    JSch jsch = new JSch();
    try {
        session = jsch.getSession(username, host, port);
        // 如果服务器连接不上,则抛出异常
        if (session == null) {
            throw DataXException.asDataXException(FtpReaderErrorCode.FAIL_LOGIN, "session is null,无法通过sftp与服务器建立链接,请检查主机名和用户名是否正确.");
        }
        // 设置密码
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(config);
        // 设置timeout时间
        session.setTimeout(timeout);
        // 通过Session建立链接
        session.connect();
        // 打开SFTP通道
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        // 建立SFTP通道的连接
        channelSftp.connect();
    //设置命令传输编码
    //String fileEncoding = System.getProperty("file.encoding");
    //channelSftp.setFilenameEncoding(fileEncoding);		
    } 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服务器", host);
                LOG.error(message);
                throw DataXException.asDataXException(FtpReaderErrorCode.FAIL_LOGIN, message, e);
            } else if (illegalArgumentException.equals(cause) || wrongPort.equals(cause)) {
                String message = String.format("请确认连接ftp服务器端口是否正确,错误的端口: [%s] ", port);
                LOG.error(message);
                throw DataXException.asDataXException(FtpReaderErrorCode.FAIL_LOGIN, message, e);
            }
        } else {
            if ("Auth fail".equals(e.getMessage())) {
                String message = String.format("与ftp服务器建立连接失败,请检查用户名和密码是否正确: [%s]", "message:host =" + host + ",username = " + username + ",port =" + port);
                LOG.error(message);
                throw DataXException.asDataXException(FtpReaderErrorCode.FAIL_LOGIN, message);
            } else {
                String message = String.format("与ftp服务器建立连接失败 : [%s]", "message:host =" + host + ",username = " + username + ",port =" + port);
                LOG.error(message);
                throw DataXException.asDataXException(FtpReaderErrorCode.FAIL_LOGIN, message, e);
            }
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties)

Example 24 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)

Example 25 with JSch

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

JSch (com.jcraft.jsch.JSch)35 Session (com.jcraft.jsch.Session)23 JSchException (com.jcraft.jsch.JSchException)16 IOException (java.io.IOException)14 Channel (com.jcraft.jsch.Channel)8 ChannelExec (com.jcraft.jsch.ChannelExec)7 File (java.io.File)7 InputStream (java.io.InputStream)7 ChannelSftp (com.jcraft.jsch.ChannelSftp)6 FileInputStream (java.io.FileInputStream)6 OutputStream (java.io.OutputStream)6 UserInfo (com.jcraft.jsch.UserInfo)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 KeyPair (com.jcraft.jsch.KeyPair)2 SftpException (com.jcraft.jsch.SftpException)2 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 UserInfoPrompted (edu.umass.cs.aws.networktools.UserInfoPrompted)2 HeadlessException (java.awt.HeadlessException)2