0

I'm trying to use Java to interface with a large batch file that uses psexec to execute commands on remote servers.

I'm able to launch the file using process builder and it works fine for most commands, but seems to be getting hung up.

One particular command from the batch file is as follows:

ECHO .
Echo Which would you like to reboot?
Echo 1-10. For computers, enter computer number.
Echo E. Exit
set /p userinp=choose a number(0-22):

but from Java I get: . Which would you like to reboot? 1-10. For computers, enter computer number. E. Exit

and then it hangs

It's clearly not reading the set line, but more importantly I haven't yet figured out how to pass input back to the subprocess.

String[] command = {"cmd", "/c", "batchfile", "restart"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:\\"));
    Process process = builder.start();

InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

Any input would be appreciated.

Perception
  • 79,279
  • 19
  • 185
  • 195
pmcfarland
  • 105
  • 1
  • 3
  • 10

2 Answers2

0

Your batch job requires that you actually provide input in order to proceed, which is why it appears to 'hang'. You need to supply this input to the process, via its output stream. A highly simplified example:

PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println("10");
writer.flush();
Perception
  • 79,279
  • 19
  • 185
  • 195
0

Your process doesn't hang, it is just waiting for some input at the command line, before to proceed.

As you are reading the output from the process via Process.getInputStream(), you can send input back to it using Process.getOutputStream().

public abstract OutputStream getOutputStream()

Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object. Implementation note: It is a good idea for the output stream to be buffered.

Returns: the output stream connected to the normal input of the subprocess.

Luigi R. Viggiano
  • 8,659
  • 7
  • 53
  • 66