0

I'm trying to use JSch in Java to connect to one of my EC2 instances, but keep getting an "UnknownHostKey" exception message. Here's is (part of) my code:

import com.jcraft.jsch.*;
import java.io.*;

public class JSchTest {

    private String serverIp;

    public void testSshConnection() {

        try {

            JSch jsch = new JSch();
            jsch.addIdentity("C:\\Users\\Administrator\\.ssh\\id_rsa");

            Session session = jsch.getSession("ec2-user", serverIp, 22);
            session.connect(30000); // <-- this is where the exception is thrown

            ChannelExec channel = (ChannelExec)session.openChannel("shell");

            // more code here...

            channel.disconnect();
            session.disconnect();

        } catch (JSchException|IOException ex) {
            ex.printStackTrace();
        }
    }

    public void setServerIp(String serverIp) {
        this.serverIp = serverIp;
    }
}

I've already added my public key to the authorized_keys file on the EC2 instance that I'm connecting to, and I know it works because I can connect to it using PuTTY. However as soon as I hit the line with the session.connect() in it, I get an exception like this:

com.jcraft.jsch.JSchException: UnknownHostKey: 10.114.2.115. RSA key fingerprint is 63:04:cf:60:4a:1d:47:35:12:0e:56:4f:5b:0a:c9:d4

What am I missing? How can I get this to connect?

soapergem
  • 9,263
  • 18
  • 96
  • 152
  • 2
    Possible duplicate of [com.jcraft.jsch.JSchException: UnknownHostKey](http://stackoverflow.com/questions/2003419/com-jcraft-jsch-jschexception-unknownhostkey) – Matt Clark Oct 21 '16 at 23:52

1 Answers1

0

Try this:

java.util.Properties config = new java.util.Properties(); 
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

As per this link.

Community
  • 1
  • 1
tom
  • 1,331
  • 1
  • 15
  • 28
  • 1
    I just tried that, and while it does work, it has me a little concerned. Isn't this telling the JSch client to essentially circumvent part of the security? – soapergem Oct 21 '16 at 23:48
  • @SoaperGEM Yes, it is. Do not do that! @tom Never suggest anyone to use the `StrictHostKeyChecking=no` without explaining security consequences! – Martin Prikryl Oct 22 '16 at 05:45
  • @MartinPrikryl I would have suggested the first option in the link I cited ("Try to ssh from the command line and accept the public key") but I don't know how to do that in EC2. Anyone? – tom Oct 22 '16 at 12:46