I want to be able to retrieve the host key of a remote SSH host using Java code. Is there any library that does this, I looked into JSch but couldn’t find what I wanted.
I am aware that I can run the terminal command ssh-keyscan <hostname>
through Java, but I want this to be the last resort. Seeking better solutions.
Advertisement
Answer
With JSch you can do it like this:
Implement
HostKeyRepository
interface in a way that thecheck
method stores itskey
argument and the method returnsNOT_INCLUDED
.public class HostKeyStore implements HostKeyRepository { public byte[] key; int check(String host, byte[] key) { this.key = key; return NOT_INCLUDED; } // dummy implementations of the other methods }
Start a connection to the server. Your
HostKeyRepository.check
implementation will be called with the server’s host key. And the connection will not happen, as the method returnedNOT_INCLUDED
.
Though make sure you understand what you are doing. This makes sense only if you want to persist the host key for future reference. Do not try to bypass or automate a host key check this way. You would lose a protection against MITM attacks.
If you aim to persist the host key, consider using a well-defined mechanism for that, the known_hosts
file. JSch can both read and update it, you do not have to implement it explicitly.
Also, if your goal is to allow the user to check the host key, JSch also has a mechanism for that, set the StrictHostKeyChecking=ask
and implement UserInfo.promptYesNo
.