Search in sources :

Example 91 with JSch

use of com.jcraft.jsch.JSch in project litle-sdk-for-java by Vantiv.

the class Communication method receiveLitleRequestResponseFileFromSFTP.

/**
 * Grabs the response file from Litle's sFTP server. This method is blocking! It will continue to poll until the timeout has elapsed
 * or the file has been retrieved!
 * @param requestFile
 * @param responseFile
 * @param configuration
 * @throws IOException
 */
public void receiveLitleRequestResponseFileFromSFTP(File requestFile, File responseFile, Properties configuration) throws IOException {
    String username = configuration.getProperty("sftpUsername");
    String password = configuration.getProperty("sftpPassword");
    String hostname = configuration.getProperty("batchHost");
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = null;
    Session session = null;
    try {
        jsch = new JSch();
        session = jsch.getSession(username, hostname);
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    Channel channel = null;
    try {
        channel = session.openChannel("sftp");
        channel.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    ChannelSftp sftp = (ChannelSftp) channel;
    Long start = System.currentTimeMillis();
    Long timeout = Long.parseLong(configuration.getProperty("sftpTimeout"));
    System.out.println("Retrieving from sFTP...");
    while (System.currentTimeMillis() - start < timeout) {
        try {
            Thread.sleep(45000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean success = true;
        try {
            sftp.get("outbound/" + requestFile.getName() + ".asc", responseFile.getAbsolutePath());
        } catch (SftpException e) {
            success = false;
            System.out.println(e);
        }
        if (success) {
            try {
                sftp.rm("outbound/" + requestFile.getName() + ".asc");
            } catch (SftpException e) {
                throw new LitleBatchException("Exception SFTP operation", e);
            }
            break;
        }
        System.out.print(".");
    }
    boolean printxml = configuration.getProperty("printxml") != null && configuration.getProperty("printxml").equalsIgnoreCase("true");
    if (printxml) {
        BufferedReader reader = new BufferedReader(new FileReader(responseFile));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
    channel.disconnect();
    session.disconnect();
}
Also used : JSchException(com.jcraft.jsch.JSchException) Properties(java.util.Properties) Channel(com.jcraft.jsch.Channel) SftpException(com.jcraft.jsch.SftpException) Properties(java.util.Properties) JSch(com.jcraft.jsch.JSch) ChannelSftp(com.jcraft.jsch.ChannelSftp) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Session(com.jcraft.jsch.Session)

Example 92 with JSch

use of com.jcraft.jsch.JSch in project halyard by spinnaker.

the class AppengineAccountValidator method validate.

@Override
public void validate(ConfigProblemSetBuilder p, AppengineAccount account) {
    String jsonKey = null;
    String jsonPath = account.getJsonPath();
    String project = account.getProject();
    String knownHostsPath = account.getSshKnownHostsFilePath();
    AppengineNamedAccountCredentials credentials = null;
    boolean hasPassword = account.getGitHttpsPassword() != null;
    boolean hasUsername = account.getGitHttpsUsername() != null && !account.getGitHttpsUsername().isEmpty();
    if (hasPassword != hasUsername) {
        if (!hasUsername) {
            p.addProblem(Severity.ERROR, "Git HTTPS password supplied without git HTTPS username.");
        } else {
            p.addProblem(Severity.ERROR, "Git HTTPS username supplied without git HTTPS password.");
        }
    }
    boolean hasSshPrivateKeyPassphrase = account.getSshPrivateKeyPassphrase() != null;
    boolean hasSshPrivateKeyFilePath = account.getSshPrivateKeyFilePath() != null && !account.getSshPrivateKeyFilePath().isEmpty();
    if (hasSshPrivateKeyPassphrase != hasSshPrivateKeyFilePath) {
        if (!hasSshPrivateKeyFilePath) {
            p.addProblem(Severity.ERROR, "SSH private key passphrase supplied without SSH private key filepath.");
        } else {
            p.addProblem(Severity.ERROR, "SSH private key filepath supplied without SSH private key passphrase.");
        }
    } else if (hasSshPrivateKeyPassphrase && hasSshPrivateKeyFilePath) {
        String sshPrivateKey = ValidatingFileReader.contents(p, account.getSshPrivateKeyFilePath());
        if (sshPrivateKey == null) {
            return;
        } else if (sshPrivateKey.isEmpty()) {
            p.addProblem(Severity.WARNING, "The supplied SSH private key file is empty.");
        } else {
            try {
                // Assumes that the public key is sitting next to the private key with the extension ".pub".
                KeyPair keyPair = KeyPair.load(new JSch(), account.getSshPrivateKeyFilePath());
                boolean decrypted = keyPair.decrypt(account.getSshPrivateKeyPassphrase());
                if (!decrypted) {
                    p.addProblem(Severity.ERROR, "Could not unlock SSH public/private keypair with supplied passphrase.");
                }
            } catch (JSchException e) {
                p.addProblem(Severity.ERROR, "Could not unlock SSH public/private keypair: " + e.getMessage() + ".");
            }
        }
    }
    if (knownHostsPath != null && !knownHostsPath.isEmpty()) {
        String knownHosts = ValidatingFileReader.contents(p, knownHostsPath);
        if (knownHosts == null) {
            return;
        }
        if (knownHosts.isEmpty()) {
            p.addProblem(Severity.WARNING, "The supplied known_hosts file is empty.");
        }
    }
    if (jsonPath != null && !jsonPath.isEmpty()) {
        jsonKey = ValidatingFileReader.contents(p, account.getJsonPath());
        if (jsonKey == null) {
            return;
        }
        if (jsonKey.isEmpty()) {
            p.addProblem(Severity.WARNING, "The supplied credentials file is empty.");
        }
    }
    if (jsonPath != null && !jsonPath.isEmpty() && account.isSshTrustUnknownHosts()) {
        p.addProblem(Severity.WARNING, "You have supplied a known_hosts file path and set the `--ssh-trust-unknown-hosts` flag to true." + " Spinnaker will ignore your `--ssh-trust-unknown-hosts` flag.").setRemediation("Run `--ssh-trust-unknown-hosts false`.");
    }
    if (account.getProject() == null || account.getProject().isEmpty()) {
        p.addProblem(Severity.ERROR, "No appengine project supplied.");
        return;
    }
    try {
        credentials = new AppengineNamedAccountCredentials.Builder().jsonKey(jsonKey).project(project).region("halyard").applicationName("halyard " + halyardVersion).build();
    } catch (Exception e) {
        p.addProblem(Severity.ERROR, "Error instantiating appengine credentials: " + e.getMessage() + ".");
        return;
    }
    try {
        credentials.getAppengine().apps().get(project).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == 404) {
            p.addProblem(Severity.ERROR, "No appengine application found for project " + project + ".").setRemediation("Run `gcloud app create --region <region>` to create an appengine application.");
        } else {
            p.addProblem(Severity.ERROR, "Failed to connect to appengine Admin API: " + e.getMessage() + ".");
        }
    } catch (Exception e) {
        p.addProblem(Severity.ERROR, "Failed to connect to appengine Admin API: " + e.getMessage() + ".");
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) KeyPair(com.jcraft.jsch.KeyPair) ConfigProblemSetBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemSetBuilder) AppengineNamedAccountCredentials(com.netflix.spinnaker.clouddriver.appengine.security.AppengineNamedAccountCredentials) JSch(com.jcraft.jsch.JSch) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) JSchException(com.jcraft.jsch.JSchException)

Example 93 with JSch

use of com.jcraft.jsch.JSch in project spring-integration by spring-projects.

the class SftpOutboundTests method testSharedSession.

@Test
public void testSharedSession() throws Exception {
    JSch jsch = spy(new JSch());
    Constructor<com.jcraft.jsch.Session> ctor = com.jcraft.jsch.Session.class.getDeclaredConstructor(JSch.class, String.class, String.class, int.class);
    ctor.setAccessible(true);
    com.jcraft.jsch.Session jschSession1 = spy(ctor.newInstance(jsch, "foo", "host", 22));
    com.jcraft.jsch.Session jschSession2 = spy(ctor.newInstance(jsch, "foo", "host", 22));
    willAnswer(invocation -> {
        new DirectFieldAccessor(jschSession1).setPropertyValue("isConnected", true);
        return null;
    }).given(jschSession1).connect();
    willAnswer(invocation -> {
        new DirectFieldAccessor(jschSession2).setPropertyValue("isConnected", true);
        return null;
    }).given(jschSession2).connect();
    when(jsch.getSession("foo", "host", 22)).thenReturn(jschSession1, jschSession2);
    final ChannelSftp channel1 = spy(new ChannelSftp());
    doReturn("channel1").when(channel1).toString();
    final ChannelSftp channel2 = spy(new ChannelSftp());
    doReturn("channel2").when(channel2).toString();
    new DirectFieldAccessor(channel1).setPropertyValue("session", jschSession1);
    new DirectFieldAccessor(channel2).setPropertyValue("session", jschSession1);
    // Can't use when(session.open()) with a spy
    final AtomicInteger n = new AtomicInteger();
    doAnswer(invocation -> n.getAndIncrement() == 0 ? channel1 : channel2).when(jschSession1).openChannel("sftp");
    DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(jsch, true);
    factory.setHost("host");
    factory.setUser("foo");
    factory.setPassword("bar");
    noopConnect(channel1);
    noopConnect(channel2);
    Session<LsEntry> s1 = factory.getSession();
    Session<LsEntry> s2 = factory.getSession();
    assertSame(TestUtils.getPropertyValue(s1, "jschSession"), TestUtils.getPropertyValue(s2, "jschSession"));
    assertSame(channel1, TestUtils.getPropertyValue(s1, "channel"));
    assertSame(channel2, TestUtils.getPropertyValue(s2, "channel"));
}
Also used : JSch(com.jcraft.jsch.JSch) DefaultSftpSessionFactory(org.springframework.integration.sftp.session.DefaultSftpSessionFactory) ChannelSftp(com.jcraft.jsch.ChannelSftp) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry) Session(org.springframework.integration.file.remote.session.Session) SftpSession(org.springframework.integration.sftp.session.SftpSession) Test(org.junit.Test)

Example 94 with JSch

use of com.jcraft.jsch.JSch in project sw360portal by sw360.

the class FossologySettingsTest method testKeyIsAValidPrivateKey.

@Test
public void testKeyIsAValidPrivateKey() throws Exception {
    final String msg = /* this tests that the */
    "Private key defined in property files";
    final byte[] fossologyPrivateKey = fossologySettings.getFossologyPrivateKey();
    assertThat(msg + "is not readable", fossologyPrivateKey, notNullValue());
    assertThat(msg + "is empty", fossologyPrivateKey.length, is(greaterThan(0)));
    try {
        final JSch jSch = new JSch();
        jSch.addIdentity("test", fossologyPrivateKey, null, null);
    } catch (Exception e) {
        fail(msg + "is not a valid private key");
    }
}
Also used : JSch(com.jcraft.jsch.JSch) Test(org.junit.Test)

Example 95 with JSch

use of com.jcraft.jsch.JSch in project jcabi-github by jcabi.

the class RtPublicKeysITCase method key.

/**
 * Generates a random public key for test.
 * @return The encoded SSH public key.
 * @throws Exception If a problem occurs.
 */
private String key() throws Exception {
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        final KeyPair kpair = KeyPair.genKeyPair(new JSch(), KeyPair.DSA);
        kpair.writePublicKey(stream, "");
        kpair.dispose();
    } finally {
        stream.close();
    }
    return new String(stream.toByteArray());
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JSch(com.jcraft.jsch.JSch)

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