Shell命令从Java失败,但是在手动运行时可以工作 [英] Shell command fails from java but works when run manually

查看:119
本文介绍了Shell命令从Java失败,但是在手动运行时可以工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

只需确保我什至在容器文件夹上尝试过chmod 777,所以我不认为这是权限问题.

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

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

推荐答案

如果该命令在终端上运行正常,但是从Java脚本调用时却无法正常运行,那么我要做的第一件事就是在被调用的命令上指定Bash ,看看是否可行:

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"

甚至更好:

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

这篇关于Shell命令从Java失败,但是在手动运行时可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆