使用java runtime exec运行连续的Commands Linux

时间:2013-07-23 13:57:20

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

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

3 个答案:

答案 0 :(得分:5)

在一般情况下,您需要在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; e.g。

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

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

答案 1 :(得分:2)

Javadoc for Runtime.exec()中所述:

  

在单独的进程中执行指定的字符串命令

每次通过exec()执行命令时,它都将在一个单独的子进程中执行。这也意味着返回后su立即停止存在的效果,这就是为什么whoami命令将在另一个子进程中执行,再次使用最初启动该程序的用户。

su test -c whoami

会给你你想要的结果。

答案 2 :(得分:0)

如果你想以某种方式运行多个命令,如果需要,可以在子shell中执行命令

How can I run multiple commands in just one cmd windows in Java?(使用ProcessBuilder模拟shell)