【问题标题】:Shell command fails from java but works when run manuallyShell命令从java失败,但在手动运行时有效
【发布时间】:2017-04-28 21:44:11
【问题描述】:

我正在尝试运行一些 bash 命令,这些命令在我的控制台中运行良好,但在尝试从 Java 中进行相同的命令调用时失败。该命令不返回错误并且无法生成所需的输出文件。该命令假设使用 PGP 工具 (GPG) 来解密文件并创建另一个文件。这在手动运行时有效,但不能在 java 应用程序中进行相同的 shell 调用并且没有错误。

为了确定我什至在容器文件夹上尝试了 chmod 777,所以我认为这不是权限问题。

Shell 执行程序代码(由 Mkyong.com 提供)

private static String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

实际的 Shell 命令

gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc

【问题讨论】:

  • 脚本在哪里?你向executeCommand()发送什么命令?
  • @Biffen 在“实际外壳命令”下方问题的底部......忘记我说的脚本。无论我将其打包为 .sh 文件还是执行为纯字符串,结果都是一样的。
  • 寻求调试帮助的问题('为什么这段代码不起作用?')必须包括所需的行为、特定的问题或错误以及重现它所需的最短代码在问题本身。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example
  • @Biffen 你真的阅读了描述吗?完整的代码在那里,“Actual Shell Command”以粗体突出显示?
  • 失败的性质是什么?请编辑您的问题以添加详细信息。它会抛出任何异常吗?打印任何错误信息?根本无法创建/main/decrypted-token.txt?另外,您能否从 Java 或您的 shell 代码中读取/main/token.asc?试试 `executeCommand("cat /main/token.asc") 看看是否可行。

标签: java bash shell gnupg


【解决方案1】:

如果命令在终端上运行良好,但从 Java 脚本调用时却不行,我会尝试的第一件事是在被调用的命令上指定 Bash,看看这是否可行:

bash -c "gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc"

甚至更好:

/bin/bash -c "gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc"

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 2021-03-12
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多