4

How to execute a command like this (with sudo) from Java ProcessBuilder? (I do not need to include a password because the normal user has permission to run myscript.log as root without a password.)

sudo bash /home/me/path/myscript.sh arg1 arg2 arg3 >> /var/log/path/myscript.log 2>&1

My question is how do the elements of this command get passed into the constructor of Java's ProcessBuilder?

For example, is "sudo" the first argument to the ProcessBuilder ctor, the last, or somewhere else? And how do you know where they go and which elements of the command become arguments to ProcessBuilder?

MountainX
  • 6,217
  • 8
  • 52
  • 83

1 Answers1

4

The problem here is that the redirection does not get executed in the bash command you are invoking.

Try using passing the command to execute as a string usin the -c option for bash:

sudo bash -c "/home/me/path/myscript.sh arg1 arg2 arg3 >> /var/log/path/myscript.log 2>&1"

In order to use the java ProcessBuilder with this command I would try construct it like this:

new ProcessBuilder("sudo", "bash", "-c", "/home/me/path/myscript.sh arg1 arg2 arg3 >> /var/log/path/myscript.log 2>&1");

With this use of ProcessBuilder you are basically asking it to execute the command sudo and provide to it 3 parameters. In return sudo will invoke your command like this: bash -c "...".

You might still have a problem when the process will prompt for the sudo password.

Lynch
  • 9,174
  • 2
  • 23
  • 34