使用java.lang.ProcessBuilder运行root命令

时间:2019-05-23 22:41:23

标签: java linux shell

在Linux机器上运行的Java应用程序上使用java.lang.ProcessBuilder(特别是Ubuntu 18.04),可以执行以下操作,使执行的命令能够运行,并且不会抛出 Permission Denied

代码如下:

boolean isWindows = System.getProperty("os.name")
                    .toLowerCase().startsWith("windows");
            ProcessBuilder builder = new ProcessBuilder();
            if (isWindows) {
                builder.directory(new File(System.getProperty("user.home")));
                builder.command("cmd.exe", "/c", command);
            } else {
                builder.directory(new File(System.getenv("HOME")));
                builder.command("sh", "-c", command);
            }
            Process process = builder.start();

1 个答案:

答案 0 :(得分:2)

在Ubuntu 18.04上测试:

import java.io.File;

    public class Application {

        public static void main(String[] args) throws Exception{
            boolean isWindows = System.getProperty("os.name")
                    .toLowerCase().startsWith("windows");
            ProcessBuilder builder = new ProcessBuilder();
            if (isWindows) {
                builder.directory(new File(System.getProperty("user.home")));
                builder.command("cmd.exe", "/c", "");
            } else {
                builder.directory(new File(System.getenv("HOME")));
                // i used the docker command as an example, because it needs a root access (default configuration of Docker)
                builder.command("/bin/bash", "-c", "sudo docker image ls > result.txt 2> errors.txt");
            }
            Process process = builder.start();
            // When running the command java Application in terminal, i noticed that when prompted to type the root password
            // the program exits so i decided to make the current thread sleep for 5 seconds, to give me time to type the password
            Thread.sleep(5000);
        }
    }

希望会有所帮助:)

相关问题