我正在尝试用Java编写一些东西来自动导入证书。在命令shell中输入此命令时:
keytool -import -keystore c:\.truststore -alias xenv -file cacert.pem
它问我2个问题:密码,如果我想确认。在Python中,我可以使用subprocess.Popen,如下所示:
p = subprocess.Popen("keytool","-import","-keystore","c:\\.truststore","-alias","xenv","-file","cacert.pem", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate("password\n" + "y\n")
我现在正尝试在Java中做类似的事情。经过几个小时的游戏后,我想我已走上正轨,但我无法让它发挥作用。知道我做错了什么吗?提前谢谢!
import java.io.*;
public class PropertyTest {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "keytool", "-import", "-keystore", "c:\\.truststore", "-alias", "xenv", "-file", "c:\\cacert.pem");
pb.redirectErrorStream(true);
Process p = pb.start();
OutputStream out = p.getOutputStream();
out.write("password\n".getBytes());
out.write("y\n".getBytes());
}
}
答案 0 :(得分:1)
这很有用。我把它改成了BufferedWriter并在我完成后刷新并关闭它。希望这可以帮助其他人解决类似的问题!
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "keytool", "-import", "-keystore", "c:\\.truststore", "-alias", "alias", "-file", "c:\\cacert.pem");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
out.write("allgoodthings\n");
out.write("y\n");
out.flush();
out.close();