2

How to connect to a remote machine with username and password using sshj java api?

I tried this code. What is the problem with this code?

final SSHClient ssh = new SSHClient();
        ssh.connect("192.168.0.1");
        ssh.authPassword("abcde", "fgh".toCharArray());
        try {
            final Session session = ssh.startSession();
            try {
                final Command cmd = session
                        .exec("cd /home/abcde/Desktop/");
                System.out.println(IOUtils.readFully(cmd.getInputStream())
                        .toString());
                cmd.join(5, TimeUnit.SECONDS);
                System.out.println("\n** exit status: " + cmd.getExitStatus());
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }

It is throwing this following error.

net.schmizz.sshj.transport.TransportException: [HOST_KEY_NOT_VERIFIABLE] Could not verify ssh-rsa host key with fingerprint ******** for 192.168.0.1 on port 22

4

3 回答 3

10

You solve your problem by implementing HostKeyVerifier

class NullHostKeyVerifier implements HostKeyVerifier {
    @Override
    public boolean verify(String arg0, int arg1, PublicKey arg2) {
        return true;
    }        
}

and adding this fake implementation to your SSHClient instance configuration:

...
    final SSHClient ssh = new SSHClient();
    ssh.addHostKeyVerifier(new NullHostKeyVerifier());
...
于 2012-07-23T16:27:32.367 回答
1

Insert ssh.loadKnownHosts(); or ssh.loadKnownHosts("somepath"); after instantiation of SSHClient.

Then add the machine (remote) you are trying to connect (192.168.0.1) to known_hosts file (on your machine) at the default location or at "somepath". For a Linux box default path will be /home/myuser/.ssh/known_hosts, or in a windows box c:/user/myuser/.ssh/known_hosts.

known_host is in openSSH format (ip/orhostname algorithm key commentary).

To add the machine to known_hosts:

-if you are using Linux (on your machine), just ssh to the remote machine and it will be automatically add to known_hosts.

-if you are using Windows, use bitwise tunnelier to connect to the remote machine it will store the key. Go to bitwise key manager (it will be on your start menu, bitwise folder) and export the row with the remote machine ip to openSSH format. Copy the resulting line to your known_host file.

That way you will be really validating the host key. It is also helpful in mule esb where you cannot add the nullhost verifier to the ssh connector (My case).

于 2014-01-21T20:12:16.710 回答
0

You miss ssh key, simply add

ssh.addHostKeyVerifier("10:20......");

where 10:20... from your exception: "with fingerprint ********"

于 2014-03-01T12:35:43.327 回答