can I re-add remote host to known_host using JSCH?

試著忘記壹切 提交于 2019-12-01 06:25:01

问题


I want to be able to remove the remote server key from known_hosts and add it again. The remote server gets updated often so I want to automatically remove the remote host key and add its new key to known_hosts. I can remove the key from known_hosts though it is clunky and uses a Process instead of going through JSCH. This works but I encounter this message whenever I try to access the server:

The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
RSA key fingerprint is 10:10:30:00:e7:0c:d3:18:cf:ac:42:e2:f3:51:25:bg.
Are you sure you want to continue connecting (yes/no)? 

I know it is possible to get around this message using a UserInfo but I use other ways of connecting to the remote server, such as a Process and the message would appear when I run those commands.

Is it possible to use JSCH to remove and add a host id from known_hosts?

Possibly related though it does not use jsch:

How can I write a program (script) to remove obsolete host keys from ~/.ssh/known_hosts?


回答1:


There is no need to programmatically manipulate known_hosts

ssh -oStrictHostKeyChecking=no remote-host

Or add

StrictHostKeyChecking no

to ~/.ssh/config. Read the ssh_config(5) man page for details.




回答2:


Yes you can add a remote host entry into your known_hosts file using JSch. As Jim Garrison answered, there are other ways around the issue, but here is how to do it in your code:

First, understand that as a default, if you do not specify a known_hosts file, JSch can still work, it will just create a run-time known_host file in memory, and add entrys automatically so long as Strict Host Key Checking is set to 'no'.

If you DO specify Known Hosts file, then JSch will add new entries to that file when Strict Host Key Check is set to 'no'

        JSch jsch = new JSch();

        jsch.setKnownHosts(knownHostsFile);
        logger.info("known hosts file set: " + knownHostsFile);

        jsch.addIdentity(privateKey);
        logger.info("rsa private key loaded: " + privateKey);

        Session session = jsch.getSession(user, host, port);
        java.util.Properties config = new java.util.Properties();

        // this setting will cause JSCH to automatically add all target servers' entry to the known_hosts file
        config.put("StrictHostKeyChecking", "no");  
        session.setConfig(config);

        session.connect();

This is not very secure behavior, but is a handy way to get JSCh to setup a new server entry for you. After your known hosts file is setup, I recommend turning your StrictHostKeyChecking back to yes.



来源:https://stackoverflow.com/questions/15642369/can-i-re-add-remote-host-to-known-host-using-jsch

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