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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17812322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 15:05:48  来源:igfitidea点击:

Run consecutive Commands Linux with java runtime exec

javalinuxruntime

提问by ATEF CHAREF

I need to run two commands linux using java code like this:

我需要使用这样的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();
        }

The problem is the output of the second command ("whoami") doesn't display the current user wich used on the first command ("su - test")!! is there any problem on this code please??

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

采纳答案by fvu

As stated in the Javadoc for Runtime.exec():

正如Runtime.exec()Javadoc中所述:

Executes the specified string command in a separate process.

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

each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the whoamicommand will be executed in another subprocess, again using the user that initially launched the program.

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

su test -c whoami

will give you the result you want.

会给你你想要的结果。

回答by Stephen C

In the general case, you need to run the commands in a shell. Something like this:

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

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

But in this case that's not going to work, because suis itself creating an interactive subshell. You can do this though:

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

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

or

或者

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

Another alternative is to use sudoinstead of su; e.g.

另一种选择是使用sudo而不是su; 例如

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


Note: while none of the above actually require this, it is a good idea to assemble the "command line" as an array of Strings, rather than getting execto do the "parsing". (The problem is that execs splitter does not understand shell quoting.)

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

回答by sysuser

If you want to run multiple commands in a way the commands would execute in a subshell if need be see the response here

如果您想以某种方式运行多个命令,这些命令将在子shell 中执行,如果需要,请在此处查看响应

How can I run multiple commands in just one cmd windows in Java?(using ProcessBuilder to simulate a shell)

如何在 Java 的一个 cmd 窗口中运行多个命令?(使用 ProcessBuilder 模拟一个 shell)