Tuesday, October 21, 2014

JSch: com.jcraft.jsch.jschexception unknownhostkey: rsa key fingerprint is - resolved

This exception is thrown because for security purpose, it needs to check if the host key you set in the program matches the host key in the ~/.ssh/known_hosts file.

The following code throws such an exception at the marked line.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class FileCopy {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();
            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
         
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

To fix it, you may do one of the followings.


1. Add this line of  code before you call session.connect()

          session.setConfig("StrictHostKeyChecking", "no");

2. Copy the ~/.ssh/known_hosts file from the host to your machine, and add the following line of code before you call session.connect().

         jsch.setKnownHosts("<known_hosts>");
          
-------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment