Jsch – UnknownHostKey exception
This Java example tries to use Jsch to download a file from a remote server to the local system.
pom.xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
SFTPFileTransfer.java
package com.mkyong.io.howto;
import com.jcraft.jsch.*;
public class SFTPFileTransfer {
private static final String REMOTE_HOST = "1.1.1.1";
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final int REMOTE_PORT = 22;
public static void main(String[] args) {
String localFile = "/home/mkyong/local/Test10.txt";
String remoteFile = "/home/mkyong/remote/Test.txt";
Session jschSession = null;
try {
JSch jsch = new JSch();
// Why UnknownHostKey?
jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
jschSession.setPassword(PASSWORD);
jschSession.connect();
Channel sftp = jschSession.openChannel("sftp");
sftp.connect();
ChannelSftp channelSftp = (ChannelSftp) sftp;
// download file from remote server to local
channelSftp.get(remoteFile, localFile);
channelSftp.exit();
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (jschSession != null) {
jschSession.disconnect();
}
}
System.out.println("Done");
}
}
Run the above program, and it throws UnknownHostKey
?
Terminal
com.jcraft.jsch.JSchException: UnknownHostKey: 1.1.1.1. RSA key fingerprint is ::::
at com.jcraft.jsch.Session.checkHost(Session.java:805)
at com.jcraft.jsch.Session.connect(Session.java:345)
at com.jcraft.jsch.Session.connect(Session.java:183)
at com.mkyong.io.howto.SFTPFileTransfer.initJsch(SFTPFileTransfer.java:29)
at com.mkyong.io.howto.SFTPFileTransfer.uploadFileUsingJsch(SFTPFileTransfer.java:35)
at com.mkyong.io.howto.SFTPFileTransfer.main(SFTPFileTransfer.java:16)
Solution
To solve it, we can use ssh-keyscan
to add the remote IP address or hostname into the ~/.ssh/known_hosts
Terminal
ssh-keyscan -t rsa <HOST_NAME> >> ~/.ssh/known_hosts
ssh-keyscan -t rsa <IP_ADDRESS_OF_HOST_NAME> >> ~/.ssh/known_hosts
For example,
Terminal
$ ssh-keyscan -t rsa 1.1.1.1 >> ~/.ssh/known_hosts
# 1.1.1.1:22 SSH-2.0-OpenSSH_7.4p1 Debian-10+deb9u7
Thank you Sir, this command was very helpful to solve the problem.