Search in sources :

Example 46 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project ant-ivy by apache.

the class SFTPRepository method list.

@SuppressWarnings("unchecked")
public List<String> list(String parent) throws IOException {
    try {
        ChannelSftp c = getSftpChannel(parent);
        String path = getPath(parent);
        Collection<LsEntry> r = c.ls(path);
        if (r != null) {
            if (!path.endsWith("/")) {
                path = parent + "/";
            }
            List<String> result = new ArrayList<>();
            for (LsEntry entry : r) {
                if (".".equals(entry.getFilename()) || "..".equals(entry.getFilename())) {
                    continue;
                }
                result.add(path + entry.getFilename());
            }
            return result;
        }
    } catch (SftpException | URISyntaxException e) {
        throw new IOException("Failed to return a listing for '" + parent + "'", e);
    }
    return null;
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) SftpException(com.jcraft.jsch.SftpException) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) LsEntry(com.jcraft.jsch.ChannelSftp.LsEntry)

Example 47 with ChannelSftp

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

the class Communication method sendLitleRequestFileToSFTP.

/**
 * This method sends the request file to Litle's server sFTP
 * @param requestFile
 * @param configuration
 * @throws IOException
 */
public void sendLitleRequestFileToSFTP(File requestFile, 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;
    boolean printxml = configuration.getProperty("printxml") != null && configuration.getProperty("printxml").equalsIgnoreCase("true");
    if (printxml) {
        BufferedReader reader = new BufferedReader(new FileReader(requestFile));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
    try {
        sftp.put(requestFile.getAbsolutePath(), "inbound/" + requestFile.getName() + ".prg");
        sftp.rename("inbound/" + requestFile.getName() + ".prg", "inbound/" + requestFile.getName() + ".asc");
    } catch (SftpException e) {
        throw new LitleBatchException("Exception SFTP operation", e);
    }
    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 48 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project opentest by mcdcorp.

the class PutToSftp method run.

@Override
public void run() {
    super.run();
    String sftpHost = this.readStringArgument("sftpHost");
    Integer sftpPort = this.readIntArgument("sftpPort", 22);
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    String sourceDir = this.readStringArgument("sourceDir");
    String sourceFileName = this.readStringArgument("sourceFile");
    String destinationDir = this.readStringArgument("destinationDir");
    String destinationFileName = this.readStringArgument("destinationFile", sourceFileName);
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(userName, sftpHost, sftpPort);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        this.log.trace("Connected to SFTP host");
        channel = session.openChannel("sftp");
        channel.connect();
        this.log.trace("The SFTP channel was opened and connected");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(destinationDir);
        File sourceFile = new File(sourceDir, sourceFileName);
        FileInputStream inputStream = new FileInputStream(sourceFile);
        channelSftp.put(inputStream, destinationFileName);
        inputStream.close();
    } catch (Exception ex) {
        throw new RuntimeException("SFTP transfer failed", ex);
    } finally {
        if (channelSftp != null) {
            channelSftp.exit();
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
Also used : Channel(com.jcraft.jsch.Channel) JSch(com.jcraft.jsch.JSch) FileInputStream(java.io.FileInputStream) ChannelSftp(com.jcraft.jsch.ChannelSftp) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 49 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project quickstarts by jboss-switchyard.

the class CamelFtpBindingTest method startUp.

@BeforeClass
public static void startUp() throws Exception {
    FtpServerFactory serverFactory = new FtpServerFactory();
    ListenerFactory listenerFactory = new ListenerFactory();
    listenerFactory.setPort(2222);
    serverFactory.addListener("default", listenerFactory.createListener());
    ListenerFactory sslListenerFactory = new ListenerFactory();
    sslListenerFactory.setPort(2221);
    SslConfigurationFactory ssl = new SslConfigurationFactory();
    ssl.setKeystoreFile(new File("src/test/resources/ftpserver.jks"));
    ssl.setKeystorePassword("password");
    sslListenerFactory.setSslConfiguration(ssl.createSslConfiguration());
    // Setting it to true will not read the file
    sslListenerFactory.setImplicitSsl(false);
    serverFactory.addListener("ftps", sslListenerFactory.createListener());
    PropertiesUserManagerFactory managerFactory = new PropertiesUserManagerFactory();
    managerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
    managerFactory.setFile(new File("src/test/resources/users.properties"));
    UserManager createUserManager = managerFactory.createUserManager();
    serverFactory.setUserManager(createUserManager);
    NativeFileSystemFactory fileSystemFactory = new NativeFileSystemFactory();
    fileSystemFactory.setCreateHome(true);
    serverFactory.setFileSystem(fileSystemFactory);
    File file = new File("target/ftp/ftps");
    file.mkdirs();
    file = new File("target/ftp/sftp");
    file.mkdirs();
    ftpServer = serverFactory.createServer();
    ftpServer.start();
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(2220);
    sshd.setKeyPairProvider(createTestKeyPairProvider("src/test/resources/hostkey.pem"));
    sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
    sshd.start();
    JSch sch = new JSch();
    Session session = sch.getSession("camel", "localhost", 2220);
    session.setUserInfo(new SimpleUserInfo("isMyFriend"));
    session.connect();
    ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
    c.connect();
    System.out.println("Home: " + c.getHome());
    c.chmod(777, ".");
    c.chmod(777, "target");
    c.chmod(777, "target/ftp");
    c.chmod(777, "target/ftp/sftp");
    c.disconnect();
    session.disconnect();
}
Also used : FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NamedFactory(org.apache.sshd.common.NamedFactory) JSch(com.jcraft.jsch.JSch) ClearTextPasswordEncryptor(org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor) SshServer(org.apache.sshd.SshServer) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) ChannelSftp(com.jcraft.jsch.ChannelSftp) Command(org.apache.sshd.server.Command) UserManager(org.apache.ftpserver.ftplet.UserManager) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) File(java.io.File) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) ServerSession(org.apache.sshd.server.session.ServerSession) Session(com.jcraft.jsch.Session) BeforeClass(org.junit.BeforeClass)

Example 50 with ChannelSftp

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

the class JschSshClient method copyRecursively.

private void copyRecursively(String sourceFolder, String targetFolder) throws MachineException {
    // create target dir
    try {
        int execCode = execAndGetCode("mkdir -p " + targetFolder);
        if (execCode != 0) {
            throw new MachineException(format("Creation of folder %s failed. Exit code is %s", targetFolder, execCode));
        }
    } catch (JSchException | IOException e) {
        throw new MachineException(format("Creation of folder %s failed. Error: %s", targetFolder, e.getLocalizedMessage()));
    }
    // not normalized paths don't work
    final String targetAbsolutePath = getAbsolutePath(targetFolder);
    // copy files
    ChannelSftp sftp = null;
    try {
        sftp = (ChannelSftp) session.openChannel("sftp");
        sftp.connect(connectionTimeout);
        final ChannelSftp finalSftp = sftp;
        Files.walkFileTree(Paths.get(sourceFolder), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    if (!attrs.isDirectory()) {
                        copyFile(file.toString(), Paths.get(targetAbsolutePath, file.getFileName().toString()).toString(), finalSftp);
                    } else {
                        finalSftp.mkdir(file.normalize().toString());
                    }
                } catch (MachineException | SftpException e) {
                    throw new IOException(format("Sftp copying of file %s failed. Error: %s", file, e.getLocalizedMessage()));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (JSchException | IOException e) {
        throw new MachineException("Copying failed. Error: " + e.getLocalizedMessage());
    } finally {
        if (sftp != null) {
            sftp.disconnect();
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) Path(java.nio.file.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

ChannelSftp (com.jcraft.jsch.ChannelSftp)99 SftpException (com.jcraft.jsch.SftpException)61 IOException (java.io.IOException)36 JSchException (com.jcraft.jsch.JSchException)28 Session (com.jcraft.jsch.Session)25 JSch (com.jcraft.jsch.JSch)20 Channel (com.jcraft.jsch.Channel)17 LsEntry (com.jcraft.jsch.ChannelSftp.LsEntry)17 File (java.io.File)16 Test (org.junit.Test)14 InputStream (java.io.InputStream)12 SftpATTRS (com.jcraft.jsch.SftpATTRS)11 FileNotFoundException (java.io.FileNotFoundException)9 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)8 FileInputStream (java.io.FileInputStream)7 OutputStream (java.io.OutputStream)7 Path (org.apache.hadoop.fs.Path)7 CoreException (org.eclipse.core.runtime.CoreException)7 IStatus (org.eclipse.core.runtime.IStatus)7 Status (org.eclipse.core.runtime.Status)7