0

I am trying to connect a remote server using JSch but I am getting "Auth fail" exception. Below is my code:

String user = "user.name";
String host = "hostip";
try
{
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host);
    session.setConfig("StrictHostKeyChecking", "no");
    System.out.println("Establishing Connection...");
    session.connect();
    int assinged_port=session.setPortForwardingL(lport, rhost, rport);
    System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}

However when I try to ssh from iTerm using the command ssh user.name@hostip I can successfully access the remote server using public key authentication.

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
Sanjay Bhatia
  • 47
  • 2
  • 9

2 Answers2

3

Your OpenSSH ssh command automatically uses the private key you have configured for OpenSSH in your .ssh folder.

JSch won't automatically use OpenSSH keys. You have to explicitly tell it what key to use.
See Can we use JSch for SSH key-based communication?

Also note that JSch does not support all key formats that OpenSSH do.
See "Invalid privatekey" when using JSch


Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks. For the correct (and secure) approach, see: How to resolve Java UnknownHostKey, while using JSch SFTP library?

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
1

As @martin prikryl says: JSch won't automatically use OpenSSH keys.

File file = new File(SystemUtils.getUserHome() + "/.ssh/id_rsa");
String knownHosts = SystemUtils.getUserHome() + "/.ssh/known_hosts";
jsch.setKnownHosts(knownHosts);
jsch.addIdentity(file.getPath());

SystemUtils belongs to Apache Commons Lang3 or you can use:

new File(System.getProperty("user.home"))
Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
Samt
  • 79
  • 7