SshUtil { public static boolean addHostKeyInKnownHostFile( Session session, String knownHostsFile ) throws JSchException { if ( session == null ) { logger.warn( "In addHostKeyInKnownHostFile, Session is null." ); return false; } if ( knownHostsFile == null || knownHostsFile.isEmpty() ) { logger.warn( "In addHostKeyInKnownHostFile, knownHostFile is either null or empty." ); return false; } try { session.connect(); } catch ( JSchException e ) { logger.error( "In addHostKeyInKnownHostFile, error while SSH connection to Host '{}'.", session.getHost(), e ); throw e; } finally { if ( session != null && session.isConnected() ) { session.disconnect(); } } HostKeyRepository hostKeyRepository = null; try { hostKeyRepository = getHostKeyRepository( knownHostsFile ); } catch ( JSchException e ) { logger.error( "In addHostKeyInKnownHostFile, error while getting Host Key Repository " + "from the known hosts file '{}'.", knownHostsFile, e ); throw e; } HostKey hostKey = session.getHostKey(); if ( hostKeyRepository != null ) { if ( hostKeyRepository.check( hostKey.getHost(), hostKey.getKey().getBytes() ) == HostKeyRepository.NOT_INCLUDED ) { hostKeyRepository.add( hostKey, null ); logger.debug( "In addHostKeyInKnownHostFile, Host key added for host {}.", hostKey.getHost() ); } else { logger.debug( "In addHostKeyInKnownHostFile, SSH key already exists for host {} " + "in the known hosts file '{}'.", hostKey.getHost(), knownHostsFile ); } return true; } return false; }  static String maskedPasswordString( String command ); static Session getSessionObject( String userName, String password, String hostName, int port,
                                            Properties sessionConfig ); static String executeCommand( Session sessionObj, String command ); static SshExecResult executeCommandEnhanced( Session session, String command ); static void executeCommandNoResponse( Session sessionObj, String command ); static void upload( Session session, InputStream localInputStream, String remoteFile ); static void download( Session session, OutputStream localOutputStream, String remoteFile ); static SftpATTRS lstat( Session session, String remoteFile ); static String executeCommand( Session sessionObj, String[] commands ); static boolean addHostKeyInKnownHostFile( Session session, String knownHostsFile );  }
@Test( expected = JSchException.class ) public void testAddHostKeyInKnownHostFile() throws JSchException { Properties sessionConfig = new Properties(); sessionConfig.put( "StrictHostKeyChecking", "no" ); Session session = SshUtil.getSessionObject( "username", "password", "localhost", 22, sessionConfig ); final String userHomeDir = System.getProperty( "user.home" ); final String knownHostsFile = String.format( "%s%s.ssh/known_hosts", userHomeDir, File.separator ); boolean hostKeyAdded = SshUtil.addHostKeyInKnownHostFile( session, knownHostsFile ); assertTrue( hostKeyAdded ); }