ATE*_*REF 3 java linux runtime
我需要使用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();
}
Run Code Online (Sandbox Code Playgroud)
问题是第二个命令("whoami")的输出不显示第一个命令("su - test")上使用的当前用户!! 请问这个代码有什么问题吗?
在一般情况下,您需要在shell中运行命令.像这样的东西:
Process pr = rt.exec(new String[]{"/bin/sh", "-c", "cd /tmp ; ls"});
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,这不会起作用,因为su它本身正在创建一个交互式子shell.你可以这样做:
Process pr = rt.exec(new String[]{"su", "-c", "whoami", "-", "test"});
Run Code Online (Sandbox Code Playgroud)
要么
Process pr = rt.exec(new String[]{"su", "test", "-c", "whoami"});
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用sudo而不是su; 例如
Process pr = rt.exec(new String[]{"sudo", "-u", "test", "whoami"});
Run Code Online (Sandbox Code Playgroud)
注意:虽然以上都不需exec要这样做,但最好将"命令行"组装为字符串数组,而不是进行"解析".(问题是execs splitter不理解shell引用.)
| 归档时间: |
|
| 查看次数: |
14540 次 |
| 最近记录: |