0

Using java.lang.ProcessBuilder on a Java application running on a Linux machine (Ubuntu 18.04 specifically), what can be done such that the command executed would be able to run and not throw Permission Denied.

Here's the code:

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
  • Does the user that is running your java process has the proper permissions to run that command (and access the expected folders) or do you want to use a different user for these commands? Commented May 23, 2019 at 23:05

1 Answer 1

2

Tested on 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);
        }
    }

Hope that will be helpful :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.