2010-12-15 15 views
5

necesito para ejecutar desde Java un script por lotes, lo que trasJava: La detección de mensaje para el usuario cuando se ejecuta un script por lotes desde Java

1) Una vez que se inicia se lleva a cabo una tarea larga (hasta varios segundos).

2) A continuación, aparece el mensaje "Contraseña:".

3) Luego, el usuario ingresa la contraseña y presiona la tecla Enter.

4) Luego, la secuencia de comandos completa su trabajo.

Sé cómo iniciar el script desde Java, sé cómo leer el resultado del script por lotes en Java, pero no sé cómo esperar a que aparezca el mensaje de contraseña (cómo puedo saber que la secuencia de comandos por lotes está esperando la entrada de la contraseña).

Entonces, mi pregunta es: ¿cómo saber cuándo el script por lotes ha impreso el mensaje?

Por el momento, he siguiente código:

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

Respuesta

3

Que debe hacer el trabajo:

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

¿Estás seguro de que es getOutputStream()? Por el momento, puedo ver parte del resultado del script por lotes usando input.readLine() (vea la declaración de registro en mi fragmento de código). Pero no todo, no puedo detectar el mensaje de esta manera. –

+0

mi primera respuesta fue una tontería. El javadoc explica el flujo de entrada y salida: http://download.oracle.com/javase/6/docs/api/java/lang/Process.html. – remipod

+0

Gracias por su código. Desafortunadamente, el prompt de contraseña NO es terminado por una nueva línea. Es por eso que readline no funciona en este caso. –

1

Ésta parece funcionar:

@Override 
public void run() throws IOException, InterruptedException { 
    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 batchFileOutput = ""; 

    while (input.ready()) { 
     char character = (char) input.read(); 
     batchFileOutput = batchFileOutput + character; 
    } 

    // Batch script has printed the banner 
    // Wait for the password prompt 
    while (!input.ready()) { 
     Thread.sleep(1000); 
    } 

    // The password prompt isn't terminated by a newline - that's why we can't use readLine. 
    // Instead, we need to read the stuff character by character. 
    batchFileOutput = ""; 

    while (input.ready() && (!batchFileOutput.endsWith("Password: "))) { 
     char character = (char) input.read(); 
     batchFileOutput = batchFileOutput + character; 
    } 

    // When we are here, the prompt has been printed 
    // It's time to enter the password 

    if (batchFileOutput.endsWith("Password: ")) { 
     final BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(proc.getOutputStream())); 

     writer.write(this.password); 

     // Simulate pressing of the Enter key 
     writer.newLine(); 

     // Flush the stream, otherwise it doesn't work 
     writer.flush(); 
    } 

    // Now print out the output of the batch script AFTER we have provided it with a password 
    String line; 

    while ((line = input.readLine()) != null) { 
     LOGGER.debug("proc: " + line); 
    } 

    // Print out the stuff on stderr, if the batch script has written something into it 
    final BufferedReader error = new BufferedReader(new InputStreamReader(
      proc.getErrorStream())); 

    String errorLine = null; 

    while ((errorLine = error.readLine()) != null) { 
     LOGGER.debug("proc2: " + errorLine); 
    } 

    // Wait until the program has completed 

    final int result = proc.waitFor(); 

    // Log the result 
    LOGGER.debug("result: " + result); 
} 
Cuestiones relacionadas