gpt4 book ai didi

java - 使用 java runtime exec 运行连续的命令 Linux

转载 作者:可可西里 更新时间:2023-11-01 11:43:31 25 4
gpt4 key购买 nike

我需要像这样使用 java 代码运行两个命令 Linux:

 Runtime rt = Runtime.getRuntime();


Process pr=rt.exec("su - test");
String line=null;
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

while((line=input.readLine()) != null) {

System.out.println(line);
}
pr = rt.exec("whoami");
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

line=null;

while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}

问题是第二个命令(“whoami”)的输出不显示在第一个命令(“su - test”)中使用的当前用户!请问这段代码有什么问题吗?

最佳答案

在一般情况下,您需要在 shell 中运行命令。像这样:

    Process  pr = rt.exec(new String[]{"/bin/sh", "-c", "cd /tmp ; ls"});

但在这种情况下,这是行不通的,因为 su 本身正在创建一个交互式子 shell。你可以这样做:

    Process  pr = rt.exec(new String[]{"su", "-c", "whoami", "-", "test"});

    Process  pr = rt.exec(new String[]{"su", "test", "-c", "whoami"});

另一种选择是使用sudo 代替su;例如

    Process  pr = rt.exec(new String[]{"sudo", "-u", "test", "whoami"});

注意:虽然以上都不需要这样做,但最好将“命令行”组装成字符串数组,而不是让 exec 执行“解析”。 (问题是 exec 的拆分器不理解 shell 引用。)

关于java - 使用 java runtime exec 运行连续的命令 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17812322/

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