【问题标题】:Java Command is not executedJava 命令未执行
【发布时间】:2015-01-15 19:05:17
【问题描述】:

我有一个 Java 应用程序,它应该执行一个 sh 命令。
我的命令看起来像sudo /bin/sh -c "echo 7 > /sys/class/gpio/export",当我在计算机的命令提示符下执行它时,它可以工作,但不适用于我的 Java-Programm。

程序行如下所示:

System.out.println(CmdExecutor.execute("sudo /bin/sh -c \"echo 7 > /sys/class/gpio/export\""));


public class CmdExecutor {

public static String execute(String[] cmd) {
    StringBuffer output = new StringBuffer();

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

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

    } catch (IOException | InterruptedException e) {
    }

    return output.toString();
}

public static String execute(String cmd) {
    StringBuffer output = new StringBuffer();

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

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

    } catch (IOException | InterruptedException e) {
    }

    return output.toString();
}

}

有人可以帮我吗?

【问题讨论】:

  • 尝试 ....exec(cmd.toString());
  • 很确定你需要在 sudo 时提供密码。
  • 将阅读器添加到输出流中,看看是否有错误。示例您可以找到here
  • 运行代码时会发生什么?您希望为 sudo 提供密码,还是应该在没有密码的情况下工作? sudo 或 shell 是否发出任何错误消息?你有例外吗?什么是异常和堆栈跟踪?
  • 也许这会有所帮助? stackoverflow.com/questions/18708087/…

标签: java linux


【解决方案1】:

我看到两个问题:

  • Java 中已经需要拆分多个参数。
  • 使用sudo 进行身份验证。

需要拆分多个参数。

如果您运行exec("a b"),系统将查找名为a b 的命令作为单个字符串命令名称。

如果您运行 exec("a", "b"), the system will look for a command namedaand passb` 作为该程序的参数。

所以你想做的是execute("sudo", "/bin/sh", "-c", "echo 7 > /sys/class/gpio/export")

sudo 可能需要身份验证

当您使用sudo 执行命令时,将执行身份验证。如果你在同一个进程中执行多个sudo命令,为了方便,系统会缓存认证,但基本上是需要认证的。

sudo 的身份验证通常意味着您需要提供密码。

你之所以sudo这是因为/sys/class/gpio/export拥有-w-------(200)的权限为root root所拥有,这意味着没有人可以读取它,只有root可以写入它。

你有几个选择:

  • 更改该文件的权限,以便每个人都可以编写它(不推荐):chmod a+w /sys/class/gpio/export
  • 更改该文件的权限,以便相关用户可以写入它:setfacl -m user:cher:w /sys/class/gpio/export - 请注意,这仅在您的 sysfs 使用 acl 选项挂载时才有效,通常不是。我不知道是否可以使用acl 选项挂载sysfs,我自己没有尝试过。
  • 将密码传递给 sudo 命令:exec("echo password | sudo /bin/sh -c \"echo 7 > /sys/class/gpio/export\"") 警告这是危险的!!!
  • 使用图形sudo 替换,例如kdesudo
  • 更改您的 sudoers 配置,以便相关用户无需输入 sudo 的密码 - 不推荐。

【讨论】:

  • 感谢您的回复。我不需要任何身份验证或更改目录的所有者。我只将字符串更改为字符串数组"sudo", "/bin/sh", "-c", "echo 7 > /sys/class/gpio/export"
  • 我更新了答案。我保留了sudo 部分以供参考,以防其他人遇到类似问题。
猜你喜欢
  • 1970-01-01
  • 2012-04-09
  • 2012-04-17
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多