简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM