hudi hudi -3 years ago 89
Java Question

How to solve permission when running bash command from java

When I run commands from the console everything is OK:

sudo -u oracle fgrep ...

When I run the same command from Java code using
, sudo doesn't work, and I need to set chmod to 775 or else I don't have permission to read logs.

Why doesn't this work? Is there an option to read logs without chmod 775?

Here is how I am using

ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
Process shell = pb.start();

InputStream is = shell.getInputStream();

Answer Source

Since you say chmod 775 for log file it works, it's obvious your process doesn't have permission.

You can run your java with sudo:

sudo java ClassFileName

Or just add sudo as the first string in the array that you pass to bash process:

command[0]="sudo -u oracle ";


//command[2...n]=Other params;

Assuming user oracle is in sudoers list and won't ask for password, this will run just like how it runs in commandline when you use sudo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download