Tuesday, November 26, 2013

SFTP JAVA Client

"JSch" is a library that can be used for SFTP connection. You have to follow following steps to create SFTP connection. For this secure connection, you need to download "jsch-0.1.50.jar" and add to the project.

1) Create SSH key

GitHub Shell can be used to create a SSH key pair for secure connection.

Reference :- https://github.com/

In Git Shell, execute following commands to create key pair for particular server.

ssh-keygen -t rsa -C your_machine_ip

Above command will create "id_rsa.pub" and "id_rsa" keys for connection between your PC and server.

id_rsa :- Private key of FTP client machine
id_rsa.pub :- Public key of SFTP server machine

Reference :- https://help.github.com/articles/generating-ssh-keys

2) Write code snip to create connection and store file

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SFTP {

    public static void main(String[] args) throws SftpException {

Session session = null;
        Channel channel = null;

        try {
            JSch ssh = new JSch();
            session = ssh.getSession("sujith", "192.168.2.6", 22);
            session.setPassword("sujith");

            String identityfile = "d:/.ssh/id_rsa";
            ssh.setKnownHosts("d:/.ssh/id_rsa.pub");
            ssh.addIdentity(identityfile);

            session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
            session.connect();

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

            sftp.put("d:/test.pdf", "/apps/home/sujith/");
            
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}