Baduel
Baduel

Reputation: 519

How to run shell commands with root privileges in Java

I need to run shell commands (in my case ipfw) in Java with root privileges. I use ProcessBuilder to run commands with no privileges:

Process p = new ProcessBuilder("ls","/").start();

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String s;
while((s=br.readLine()) != null) {
    System.out.println(s);
}

This code work fine but I need to run something like sudo root command. How can I do?

I need to run this program in Eclipse, Mac OS X 10.6.8

Edit: for now I use sudo java nameclass from terminal but in this way I have to manually add all the referenced classes.

Upvotes: 3

Views: 3565

Answers (1)

C. K. Young
C. K. Young

Reputation: 223193

Easy!

  1. Set up your sudoers to not require a password for ipfw:

    user = NOPASSWD: /usr/sbin/ipfw
    
  2. Use sudo as usual.

Upvotes: 6

Related Questions