Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Could not load known_hosts" exception using SSHJ

Tags:

java

ssh

sshj

I am getting an exception while using SSHJ.

Here is how I implemented it:

public static void main(String[] args) throws IOException { 
    // TODO Auto-generated method stub 
    final SSHClient ssh = new SSHClient(); 
    ssh.loadKnownHosts(); 
    ssh.connect("serverName"); 
    try{ 
        ssh.authPublickey("myUserId"); 
        final Session session = ssh.startSession(); 
        try{ 
            final Command cmd = session.exec("net send myMachineName Hello!!!"); 
            System.out.println(cmd.getOutputAsString()); 
            System.out.println("\n Exit Status: "+cmd.getExitStatus()); 
        }finally{ 
            session.close(); 
        } 
        }finally{ 
            ssh.disconnect(); 
        }    
    } 

} 

But I get the following exception:

Exception in thread "main" java.io.IOException: Could not load known_hosts
    at net.schmizz.sshj.SSHClient.loadKnownHosts(SSHClient.java:528)
    at SSHTEST.main(SSHTEST.java:25)

What am I doing wrong?

like image 638
user234194 Avatar asked Sep 02 '10 18:09

user234194


3 Answers

Remove the call to loadKnownHosts() method, which as erickson mentioned checks under ~/.ssh/known_hosts by default (you can specify the location as an argument as well though), and replace it with:

ssh.addHostKeyVerifier("public-key-fingerprint");

To find out what the fingerprint is, the twisted way would be to connect without that statement - you'll find out from the exception ;-)

like image 101
shikhar Avatar answered Nov 16 '22 22:11

shikhar


It sounds like it's trying to read a "known_hosts" file, but can't find it, or possibly it in an invalid format.

The SSH known hosts file records the public key for various hosts to thwart some spoofing attacks. Normally it resides in ~/.ssh/known_hosts. Try creating an empty file there and see if that satisfies the library.

The library documentation is likely to address the necessary configuration files.

like image 33
erickson Avatar answered Nov 16 '22 21:11

erickson


Use the folowing code

final SSHClient ssh = new SSHClient();  

ssh.addHostKeyVerifier(  
    new HostKeyVerifier() {  
        public boolean verify(String arg0, int arg1, PublicKey arg2) {  
            return true;  // don't bother verifying  
        }  
    }  
);  

ssh.connect("LocalHost");
like image 15
microag Avatar answered Nov 16 '22 20:11

microag