【问题标题】:Run root command using java.lang.ProcessBuilder使用 java.lang.ProcessBuilder 运行 root 命令
【发布时间】:2019-05-23 22:41:23
【问题描述】:

在 Linux 机器(特别是 Ubuntu 18.04)上运行的 Java 应用程序上使用 java.lang.ProcessBuilder,可以执行哪些操作以使执行的命令能够运行而不抛出 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();

【问题讨论】:

  • 运行您的 java 进程的用户是否有适当的权限来运行该命令(并访问预期的文件夹)或者您想为这些命令使用不同的用户?

标签: java linux shell


【解决方案1】:

在 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);
        }
    }

希望对您有所帮助:)

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2016-05-06
    • 2012-07-29
    • 2015-10-21
    • 2020-10-02
    • 2021-10-11
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    相关资源
    最近更新 更多