Returning Shell return values using sshj

1.7k views Asked by At

I am using sshj to connect to remote machines to retrieve various values. As I understand in sshj, when I perform the following code to retrieve the hostname of the remote machine:

SSHClient sshClient = new SSHClient();
Session session = sshClient.startSession();
Command commandObject = session.exec("hostname");

I know that I can retrieve the return values by grabbing the inputstream

session.getInputStream();

The problem that I seem to have is that, the session object (and command) is designed as a 'use once then throwaway' fashion. So, with this in mind, I want to close the session once I am finished with it to clean up the resources, i.e.

commandObject.close();

However, due to the asynchronous nature of sshj, I am unable to determine when a return value is available in the inputstream as there doesn't seem to be any callback feature built in.

The only way that I can think of getting around this issue is to sleep for a predefined period before inspecting the inputstream. However I feel as though this is merely a hack, and I hope that there is a better solution to all of this.

Has anyone had any similar issues using sshj? With any possible solutions?

Cheers!

1

There are 1 answers

3
shikhar On BEST ANSWER

You can call join() on the Session object, and when the command has exited this method will return (or if the timeout expires). Then you can check the exit code with getExitCode() -> Integer which may be null if no exit code was received.

Edit: by return values did you mean the output generated by the command? The InputStream retured by getInputStream() or getErrorStream() implement the available() method, so you can implement a solution based on that.