首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用java.lang.ProcessBuilder运行根目录命令

使用java.lang.ProcessBuilder运行根目录命令
EN

Stack Overflow用户
提问于 2019-05-24 06:41:23
回答 1查看 660关注 0票数 0

在Linux机器上运行的Java应用程序(特别是Ubuntu18.04)上使用java.lang.ProcessBuilder,可以做些什么来使执行的命令能够运行并且不会抛出权限被拒绝的

代码如下:

代码语言:javascript
复制
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();
EN

回答 1

Stack Overflow用户

发布于 2019-05-24 08:19:22

在Ubuntu 18.04上测试:

代码语言:javascript
复制
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);
        }
    }

希望这将对您有所帮助:)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56283774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档