javasshj

sshj: how to read InputStream from long-running command while command is executing


Currently I am executing command over ssh using:

val sshCmd = session.exec(command)
println(IOUtils.readFully(sshCmd.inputStream).toString())
sshCmd.join()

However, to see the output I need to wait until the command is finished.

How can I get "live" response?

I guess I can read the input stream until end of the line occurs and then print the line; however, is there already some method in the library that can help me with this?


Solution

  • It blocks and waits for the whole thing because that's what IOUtils.readFully is meant to do, it reads fully. Instead, to read line-by-line, you can do something as simple as:

     try (BufferedReader reader = new BufferedReader(new InputStreamReader(sshCmd.inputStream))) {
         String line;
         while ((line = reader.readLine()) != null) {
             System.out.println(line);
         }
     } catch (IOException e) {
         System.out.println(e);
     }