在Linux机器上运行的Java应用程序(特别是Ubuntu18.04)上使用java.lang.ProcessBuilder
,可以做些什么来使执行的命令能够运行并且不会抛出权限被拒绝的。
代码如下:
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();
发布于 2019-05-24 00:19:22
在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);
}
}
希望这将对您有所帮助:)
https://stackoverflow.com/questions/56283774
复制相似问题