Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Detecting user prompt when running a batch script from Java

I need to execute from Java a batch script, which does following

1) Once it is started it performs a lengthy (up to several seconds) task.

2) Thereafter, it displays a prompt "Password:".

3) Then, the user types in the password and presses the Enter key.

4) Then, the script completes its job.

I know how to launch the script from Java, I know how to read output of the batch script in Java, but I don't know how to wait for the password prompt to appear (how I get to know that the batch script is awaiting the password entry).

So, my question is: How to get to know when the batch script has printed the prompt?

At the moment, I have following code:

final Runtime runtime = Runtime.getRuntime();
final String command = ... ;

final Process proc = runtime.exec(command, null, this.parentDirectory);

final BufferedReader input = new BufferedReader(new InputStreamReader(
  proc.getInputStream()));

String line = null;

while ((line = input.readLine()) != null) {
 LOGGER.debug("proc: " + line);
}
like image 850
Dmitrii Pisarenko Avatar asked Dec 15 '10 13:12

Dmitrii Pisarenko


1 Answers

That should do the job:

  public static void main(final String... args) throws IOException, InterruptedException {
    final Runtime runtime = Runtime.getRuntime();
    final String command = "..."; // cmd.exe

    final Process proc = runtime.exec(command, null, new File("."));

    final BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    StringBuilder sb = new StringBuilder();
    char[] cbuf = new char[100];
    while (input.read(cbuf) != -1) {
        sb.append(cbuf);
        if (sb.toString().contains("Password:")) {
            break;
        }
        Thread.sleep(1000);
    }
    System.out.println(sb);
}
like image 67
remipod Avatar answered Oct 03 '22 07:10

remipod