Java 命令未执行

Java Command is not executed

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

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();
}

}

有人可以帮助我吗?

我看到两个问题:

  • 多个参数需要在 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 拥有 root root 拥有的权限 -w------- (200),这意味着没有人可以读取它,只有 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 的密码 - 不推荐。