1

I have two servers A and B. I want to SFTP a file from server A to B.

Public key of server A (~/.ssh/id_rsa.pub) has been added to the ~/.ssh/authorized_keys of server B.

From command line, I can SFTP from server A to B without entering password. However, from a Java client using library Jsch I am unable to make SFTP connection to server B and I am getting authentication error:

Error occurred during SFTP. Auth fail
com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:519)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at Main.main(Main.java:15)

Is there a way I can connect to server B for SFTP purposes using Java client without specifying password?

Below is my Java code for reference:

import com.jcraft.jsch.*;

public class Main {

    public static void main(String[] args) {

        JSch jsch = new JSch();
        Session session = null;

        try {
            session = jsch.getSession("processor", "remoteserver.myorg.com", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Trying to connect...");
            session.connect();
            System.out.println("Connected successfully.");

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            System.out.println("Doing SFTP...");
            sftpChannel.put("/tmp/test.txt", "/some/remote/folder");
            System.out.println("Success");
            sftpChannel.exit();
            session.disconnect();

        } catch (JSchException | SftpException e) {
            System.err.println("Error occurred during SFTP. " + e.getMessage());
            e.printStackTrace();
        }

    }
}
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62

1 Answers1

1

Use addIdentity() api in jsync and point to your private key file location.

Ref: Can we use JSch for SSH key-based communication?

   String privateKey = "~/.ssh/id_rsa";    
   jsch.addIdentity(privateKey);
   System.out.println("identity added ");    
   Session session = jsch.getSession(user, host, port);
   System.out.println("session created.");
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62
Senthil
  • 2,156
  • 1
  • 14
  • 19