tags:

views:

53

answers:

2

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?

+2  A: 

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.

erickson
Where in the server?
@user234194: Make the file on the client. The server doesn't normally check where the client is coming from (that'd be a real PITA).
Donal Fellows
+2  A: 

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 ;-)

shikhar