在c ++或java中以响应模式使用cmd

10 c++ java openssl cmd exec

我在我的c ++应用程序中使用OpenSSL,问题是如果我使用exec("Open ssl command") 那么它将执行该特定命令,但实际上这个命令是repsonsive,我的意思是它进一步询问你"Are you sure you want to do this Y/N?" 我不知道如何迎合这种情况.我怎么能使用java或C++来运行响应的命令行,任何帮助将不胜感激.谢谢

Rya*_*art 9

在Java中很容易.只是:

  1. 获取流程句柄.
  2. 读取进程'输入流以获取写入stdout的提示.
  3. 通过写入Process的输出流来响应提示.

这是一个快速的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系统属性


wim*_*ica 6

基本上,您只需要确保在命令行上输入所有必需的信息,并使用-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命令都不起作用,请在您的问题中指定它需要执行哪个命令.