There are two questions about this exception already:
- JSchException: UnknownHostKey and
- com.jcraft.jsch.JSchException: UnknownHostKey
I am using a Windows machine and trying to connect to a VM created with Vagrant running Ubuntu. Here is my code:
public static void main(String[] args) {
String host = "localhost";
String username = "vagrant";
int port = 2200;
String privateKey = "C:\\keys\\openSSH_pair1\\open_ssh_private";
JSch js = new JSch();
try {
js.addIdentity(privateKey, "pass");
js.setKnownHosts("C:\\Users\\user\\.ssh\\known_hosts");
Session session = js.getSession(username, host, port);
session.connect();
System.out.println("Connected");
} catch (JSchException e) {
e.printStackTrace();
}
}
@Pascal suggests setting strictHostKeyChecking
to no
, which works for me, but this is not the preferred solution. His preferred solution is to SSH from the command line so that the host will be added to the known_hosts
file. I have Git installed and executed ssh -i openSSH_pair1\open_ssh_private vagrant@localhost -p 2200
and received this output before being prompted for the pass phrase and establishing a connection
The authenticity of host '[localhost]:2200 ([127.0.0.1]:2200)' can't be established. ECDSA key fingerprint is 11:5d:55:29:8a:77:d8:08:b4:00:9b:a3:61:93:fe:e5. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '[localhost]:2200' (ECDSA) to the list of known hosts.
So now my known_hosts
file in git_home\.ssh
contains an entry for localhost:2200
, I also placed the known_hosts
file into user_home\.ssh
. I also put my private key on the VM I'm trying to ssh into and ran this to generate a public key and add it to the authorized_keys
ssh-keygen -y -f open_ssh_private > open_ssh_gen.pub
cat open_ssh_gen.pub >> ~/.ssh/authorized_keys
However I still get this exception
com.jcraft.jsch.JSchException: UnknownHostKey: localhost. RSA key fingerprint is 50:db:75:ba:11:2f:43:c9:ab:14:40:6d:7f:a1:ee:e3
at com.jcraft.jsch.Session.checkHost(Session.java:797)
at com.jcraft.jsch.Session.connect(Session.java:342)
at com.jcraft.jsch.Session.connect(Session.java:183)
at connect.Main.main(Main.java:24)
The answer to the other question suggests adding the below which doesn't work for me either
js.setKnownHosts("C:\\Users\\user\\.ssh\\known_hosts");