在Java中很容易.只是:
这是一个快速的Groovy示例,因为它比Java更容易:
def cmd = ... // the command you want to run
def process = cmd.execute()
def processStdout = new Scanner(process.inputStream)
def processStdin = process.outputStream
def outputLine = processStdout.nextLine()
if (outputLine == 'some prompt written to stdout') {
processStdin << 'your response\n'
}
Run Code Online (Sandbox Code Playgroud)
如果您不能关注Groovy,我可以将它扩展为Java.
请注意,此示例不处理潜在的重要任务,即确保嵌套进程的stdout和stderr被完全消耗以防止阻塞,也不处理确保进程干净地退出.
更新:这是Java中的相同内容:
import java.io.OutputStream;
import java.util.Scanner;
public class SubprocessIO {
public static void main(String[] args) throws Exception {
String[] cmd = { ... your command as a series of strings ... };
Process process = Runtime.getRuntime().exec(cmd);
Scanner processStdout = new Scanner(process.getInputStream());
OutputStream processStdin = process.getOutputStream();
String outputLine = processStdout.nextLine();
if (outputLine.equals("some prompt written to stdout")) {
processStdin.write("your response\n".getBytes());
processStdin.flush();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我忘了在第一轮\n中记录响应是至关重要的,假设应用程序期望您输入内容然后按Enter键.此外,您可能最好使用line.separator系统属性
基本上,您只需要确保在命令行上输入所有必需的信息,并使用-batch以避免进一步的问题,例如:
openssl ca -days 3650 -out client.crt -in client.csr -config \path\to\configs -batch -passin pass:PASSWORD -key password
Run Code Online (Sandbox Code Playgroud)
如果这对任何特定的openssl命令都不起作用,请在您的问题中指定它需要执行哪个命令.