Funkydiddykong Funkydiddykong - 5 months ago 35
Java Question

Runtime Process BufferedReader not outputting all lines (Psexec)

I am trying to read the output of Psexec into Java using a BufferedReader on a Process InputStream for use on a network however it is only outputting the first line.

Runtime rt = Runtime.getRuntime();

try {
Process p = rt.exec("C:\\Users\\*****\\Desktop\\PS\\Psexec \\\\" + "******" + " -u ****** -p ****** cmd /c dir D:\\");

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

log.add("Computer: " + address);

String s = null;
while ((s = stdInput.readLine()) != null) {
log.add(s);
}

} catch (IOException e) {
e.printStackTrace();
}


What would be the reason for this happening and how would this be fixed?

Answer

So, I spent some time playing around with this, using ProcessBuilder.

I tried redirecting the IO through the INHERITED and PIPE options, but could not get it to display the output of the remote command (the psexec content was fine)

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class Test1 {

    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder(
                        "C:\\Users\\shane\\Downloads\\PSTools\\PsExec.exe",
                        "\\\\builder",
                        "-u",
                        "xxx",
                        "-p",
                        "xxx",
                        "cmd", 
                        "/c", "dir", "c:\\"
        );
        try {
            Process p = pb.start();
            StreamConsumer.consume(p.getErrorStream());
            StreamConsumer.consume(p.getInputStream());
            System.out.println("Exited with :" + p.waitFor());
        } catch (IOException | InterruptedException exp) {
            exp.printStackTrace();
        }
    }

    public static class StreamConsumer implements Runnable {

        private InputStream is;

        public StreamConsumer(InputStream is) {
            this.is = is;
        }

        public static void consume(InputStream is) {
            StreamConsumer consumer = new StreamConsumer(is);
            new Thread(consumer).start();
        }

        @Override
        public void run() {
            try {
                int in = -1;
                while ((in = is.read()) != -1) {
                    System.out.print((char)in);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }
        }

    }

}

I even tried redirecting the InputStreams to File without any success. It would seem that whatever mechanism psexec is using to stream the results from the remote machine don't seem to be picked up by Java.

You might try PAExec which did work, but didn't seem to wait to exit after the remote command exited...