/sys/class/gpio/export" 并且当我在计算机的命令提示-6ren">
gpt4 book ai didi

未执行 Java 命令

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:36 25 4
gpt4 key购买 nike

我有一个 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();
}

有人可以帮助我吗?

最佳答案

我看到两个问题:

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

需要拆分多个参数。

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

如果您运行 exec("a", "b"),系统将查找名为a的命令并将b` 作为参数传递给该程序。

所以你想要做的是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 输入密码 - 不推荐。

关于未执行 Java 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com