Posts which you will also like.

Tuesday, December 25, 2012

How to create SFTP connection using java ?



In this blog post we will learn how to create a secure FTP connection using java.SFTP is much more secure than its predecessor FTP since SFTP is based on SSH.
Here We will develop a SFTP client.Basically SFTP clients are programs that use SSH to access, manage, and transfer files. SFTP clients are functionally similar to FTP clients, but they use different protocols.
To create a SFTP connection to a server for file transfer or any other FTP operation we will use an open source library called JSCh. You can download this library from http://www.jcraft.com/
Add this library to your class path and start creating the program.
This example shows how to get a file from the server using SFTP.
package com.techy.rajeev;

import com.jcraft.jsch.*;

    /**
     * @param args
     */

    public class SFTPTest {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        String username="";//Put your username here
        String password="";//Put your password here
        String host="";//Hostname
        String sourceFile="";//Path of file on the server
        String destFile="";//Path of local file
        try {
            session = jsch.getSession(username,host,22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            sftpChannel.get(sourceFile,destFile);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace(); 
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

No comments:

Post a Comment

Your comment may wait for moderation....

DMCA.com Protected by Copyscape Online Plagiarism Tool