ProcessBuilder并运行包含空格的OpenSSL命令

我在Ubuntu环境中使用jar执行openSSL命令时遇到问题。我的结论是,发生这种情况是由于文件路径中的空间正在作为命令中的参数(例如,以下命令中的SHA

256)传递。我已经使用了进程和ProcessBuilder类来执行相同的操作:

String certFilePath = "/home/mplusuer/Desktop/Nishant/210515/TestData/TestData/SHA 256/nishant.cer"

String []cmdGetAlgorithm = new String[3];

cmdGetAlgorithm[0] = "openssl x509 -in";

cmdGetAlgorithm[1] = certFilePath;

cmdGetAlgorithm[2] = "-noout -text -certopt no_subject,no_header,no_version,no_serial,no_validity,no_subject,no_issuer,no_pubkey,no_sigdump,no_aux,no_extensions";

ProcessBuilder pb = new ProcessBuilder(cmdGetAlgorithm[0], cmdGetAlgorithm[1],cmdGetAlgorithm[2]);

// setup other options ...

Process processGetAlgorithm = pb.start();

processGetAlgorithm.waitFor();

Runtime runtime = Runtime.getRuntime();

String cmdGetAlgorithm = "openssl x509 -in "

+ certFilePAth

+ " -noout -text -certopt no_subject,no_header,no_version,no_serial,no_validity,no_subject,no_issuer,no_pubkey,no_sigdump,no_aux,no_extensions ";

Process processGetAlgorithm = runtime.exec(cmdGetAlgorithm);

最终命令如下所示,如果在命令提示符下单独执行,则工作正常,但使用Java代码执行时失败:

openssl x509 -in /home/mplusuer/Desktop/Nishant/210515/TestData/TestData/SHA 256/suketu.cer  \

-noout -text -certopt no_subject,no_header,no_version,no_serial,no_validity,no_subject, \

no_issuer,no_pubkey,no_sigdump,no_aux,no_extensions

我也使用以下方法解决了此问题,但是没有按预期工作:

String quoted = "\"" + certFilePath + "\"";

String escaped = certFilePath.replace(" ", "\\ ");

请查看并帮助我解决该问题。

回答:

cmdGetAlgorithm[0] = "openssl x509 -in";

...

正如@immibis在评论中所述,arg[0]是程序名称。因此向量应类似于:

cmdArg[0] = "/usr/local/ssl/bin/openssl";

cmdArg[1] = "x509";

cmdArg[2] = "-in";

cmdArg[3] = certFilePAth;

cmdArg[4] = "-noout"

cmdArg[5] = "-text";

cmdArg[6] = "-certopt";

cmdArg[7] = "no_subject,no_header,no_version,no_serial,no_validity," +

"no_issuer,no_pubkey,no_sigdump,no_aux,no_extensions ";

您应始终指定可执行文件的完整文件名,以确保您正在运行预期的可执行文件,而不是对手植入的文件。

以上是 ProcessBuilder并运行包含空格的OpenSSL命令 的全部内容, 来源链接: utcz.com/qa/406555.html

回到顶部