簡體   English   中英

Shell 命令從 Java 失敗,但在手動運行時有效

[英]Shell command fails from java but works when run manually

我正在嘗試運行一些 bash 命令,這些命令在我的控制台中運行良好,但在嘗試從 Java 中進行相同的命令調用時失敗。 該命令不會返回任何錯誤並且無法生成所需的輸出文件。 該命令假設使用 PGP 工具 (GPG) 解密一個文件並創建另一個文件。 這在手動運行時有效,但不能在執行相同 shell 調用且沒有錯誤的 Java 應用程序中運行。

為了確保我什至在容器文件夾上嘗試了 chmod 777,所以我認為這不是權限問題。

Shell Executor Code(由 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

如果該命令在終端上運行良好,但在從 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM