Introduction

JSch - short form for Java Secure channel- is a free SSH client library for the Java environment. In this post we will talk about how do deactivate the checking for the known_hosts-file in JSch. First lets take a look at some example code:

Example code:

private ChannelSftp openSession() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts(sshKnownHostsFile);
    int port = Integer.valueOf(somePortFromPropertiesFile);

    Session session = jsch.getSession(user, host, port);
    session.setPassword(EncryptionUtil.decrypt(passwordFromPropertiesFile));

    session.connect();
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp channelSftp = (ChannelSftp) channel;

    return channelSftp;
}

The problem

Normally you would think that it is enough to comment out the jsch.setKnownHosts(sshKnownHosts); line, but this would be too easy, right? ;) It still will check the known_hosts-file and throw some errors, if something goes wrong.

Workaround

The code snippet shows how to explicitly deactivate the checking of the known_hosts-file in JSch.

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

So the endresult looks like this:

private ChannelSftp openSession() throws JSchException {
    JSch jsch = new JSch();
    //jsch.setKnownHosts(sshKnownHostsFile);
    int port = Integer.valueOf(somePortFromPropertiesFile);

    Session session = jsch.getSession(user, host, port);

    // Remove known_hosts setting.
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    // END

    session.setPassword(EncryptionUtil.decrypt(passwordFromPropertiesFile));
    session.connect();
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp channelSftp = (ChannelSftp) channel;

    return channelSftp;
}