Shell command fails from java but works when run m

2019-09-07 19:30发布

I'm trying to run some bash commands that works fine from my console but fails when trying to make the same command call from within Java. The command returns no errors and fails to produce the desired output file. The command is suppose to use a PGP tool (GPG) to decrypt a a file and create another file. This works when run manually but not from within a java app making the same shell call and with no errors.

Just to be sure I even tried chmod 777 on the container folder so I don't think its a permission issue.

Shell Executor Code (Coutesy of 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();

}

Actual Shell Command

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

1条回答
Rolldiameter
2楼-- · 2019-09-07 20:08

If the command works fine on the terminal but not when calling from the Java script, the first thing I would try would be to specify Bash on the command being called, see if this works:

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

Or even better:

/bin/bash -c "gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc"
查看更多
登录 后发表回答