JSchException: UnknownHostKey

时间秒杀一切 提交于 2019-12-11 01:18:23

问题


I'm trying to use Jsch to establish an SSH connection in Java. I have set "StrictHostKeyChecking" to yes. I understand that the hostkey of the server has to be obtained before hand and store in the hostkey file before the first attempt to connect to the server. How can I get the HostKey of the server. My code produces the following exception:

com.jcraft.jsch.JSchException: UnknownHostKey: ASY-PC RSA key fingerprint is 22:fb:ee:fe:18:cd:aa:9a:9c:78:89:9f:b4:78:75:b4

How can I make connection with StrictHostKeyChecking Yes. Here is my code.

package sshexample;

import com.jcraft.jsch.*;
import java.io.*;

public class SSHexample 
{
public static void main(String[] args) 
{
    String user = "user";
    String password = "password";
    String host = "192.168.100.103";
    int port=22;
    try
    {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "yes");
        System.out.println("Establishing Connection...");
        session.connect();
        System.out.println("Connection established.");
        System.out.println("Crating SFTP Channel.");
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
}catch(Exception e) {
e.printStackTrace();
}
}

回答1:


You have to supply a KnownHostKeys file by calling following function

jsch.setKnownHosts(new FileInputStream(knownHostsFile));

this file should have all the the known hosts' fingerprints separated by new lines.

for example

hostname,10.1.1.120, ssh-rsa AAAAC3NzaC1yc2EAAAADAQABAAABAQCi5b647581SwC0uUDQw1ENjKSz3rhJMRRZEgIjHylvF4fbuAEzj645YoAf9SItb51MhetFAJrq98jYsHpedSm3IoMG+aR/P1CjsBz1RtJKlfR2NfYDCZ7Dyx11P8FnJbwbYif/GeG0xEujekwF1pyL0tNPmf0H4/GPR4mwrv/llGlB3Lo3BzxrGtl4f4X/oSHDoo7FrQkDwqOfeSM++3vPPHxyVO5zhFJ5u9f7M/uuxUeHS+YS5JWAI7NLXKgbiM9dluGzZU/6Awo3ux4x5ojL+kf29JEVxK+o6GfW2bIW+LhgIGZNThnN5nHzBVfNNHvQ7KC5ic0h2z2gbVpwJr1h

you can obtain this key from server by using any sftp client however following command may help if you are using linux or unix

ssh-keyscan -t rsa 10.1.1.120



回答2:


After a few minutes of testing i found a solution for this. If you don't want to use the default knownHost File, just create your own

This how the file could look:

192.168.0.1 ssh-rsa
AAAAC3NzaC1yc2EAAAADAQABAAABAQCi5b647581SwC0uUDQw1ENjKSz3rhJMRRZEgIjHylvF4fbuAEzj645YoAf9SI
tb51MhetFAJrq98jYsHpedSm3IoMG+aR/P1CjsBz1RtJKlfR2NfYDCZ7Dyx11P8FnJbwbYif
/GeG0xEujekwF1pyL0tNPmf0H4/GPR4mwrv/llGlB3Lo3BzxrGtl4f4X
/oSHDoo7FrQkDwqOfeSM++3vPPHxyVO5zhFJ5u9f7M/uuxUeHS+YS5JWAI7NLXKgbiM9dluGzZU
/6Awo3ux4x5ojL+kf29JEVxK+o6GfW2bIW+LhgIGZNThnN5nHzBVfNNHvQ7KC5ic0h2z2gbVpwJr1h

And all those entries are separated by new lines. You get the RSA key that you want by asking your session:

session=null;
com.jcraft.jsch.Channel channel =null;
try{
    ssh=new JSch();
    ssh.setKnownHosts("test");
    session=ssh.getSession(userTextField.getText(),ip,22);
    session.setPassword(passwordField1.getText());

    System.out.println(session.getHostKey());
    session.connect();
    channel=session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftp=(ChannelSftp) channel;
    System.out.println(sftp.getHome());
    for (Object o : sftp.ls(sftp.getHome())) {
        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
    }

    } catch (JSchException e1) {
        e1.printStackTrace();
        addHost(session.getHostKey().getKey());
    } catch (SftpException e1) {
        e1.printStackTrace();
    }
}

private void addHost(String key){
    try {
        FileWriter tmpwriter=new FileWriter("test",true);

            tmpwriter.append(ip + " ssh-rsa " + key+"\n");
            System.out.println(ip + " ssh-rsa " + key);

        tmpwriter.flush();
        tmpwriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

So session.getHostKey().getKey() is what you want to call to get the key.

You also need to call session.connect(); before you ask for the key and handle it in the catch.




回答3:


As most the of the answers suggest you have to provide know host file but fail to address how to get it. You simply need to SSH to the host.

Eg ssh user@192.168.100.103

when prompted provide password. For first time connection it will you to save the hosts ssh key fingerprint. Once you are connected you can find your known_host file at

user/.ssh/known_hosts

For me on windows path is C:\Users\athakur\.ssh\known_hosts. You can directly use this file. Or edit the file and pick up entry from it corresponding to your IP address which would look something like

192.168.100.103 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1UsgiLH5hjIScZlqPA4kNhPoXAX00mMv65N8qTvYd1D1M5DwWtTTcxK4w0wGKKVA7RERzWbtjPpSomJwT1LofZr+qafLdiEvhirIXVYHSWZqp6zTJW0jzk3p07ugjoHV3YUWKDzOaiFuOMslt8hD7pZv8nhOYfxBZdsVHdukYRP8MADXC0ZgOD5ZYZ0EglaQJYPG7n73PSMZWZT/oafUcx6bFiRF4QsXaguWuu6umX9gaV7VvoyMJg+kxPAKnGDFY7If61AG7vAchUUhlQ44SB1FFr25y+qeUg2NGqAxH/Z/ZAfvZ+pDv3Cd9s+KCnEIqxyxY/sPQ2zCvwf0Z9fTeQ==

Note : Host machines SSH fingerprint (based on hosts public key that you can find at /etc/ssh/ssh_host_rsa_key.pub) may change in SSH is reinstalled in that machine. Or you may encounter MIM attack (even it is for testing sake). In such cases you will have to pick new entry in same way mentioned above.




回答4:


Maybe it's no more relevant but in my case, the similar problem was happened with docker-compose.yml in container, that was build from spring-boot application that 100 % worked locally

config-service:
    image: <host>/<bla>-config-service:<version>
    hostname: config-service
    ports:
        - 3000:3000
    depends_on:
        - discovery
    environment:
        - CONSUL_HOST=discovery
        - CONSUL_PORT=<port> 
        - CONFIG_GIT_URI=git@<host>:<group>/<repository>.git
        - CONFIG_GIT_BRANCH=development
    volumes:
        - ~/.ssh/:/root/.ssh/:ro

Solution was to apply hack on ~/.ssh folder.

chcon -Rt svirt_sandbox_file_t ~/.ssh

After that I suppose volumes was correctly mapped between docker container and local machine, and described exception was gone.



来源:https://stackoverflow.com/questions/19063115/jschexception-unknownhostkey

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!