Monday, December 6, 2010

Java: run command as root by Runtime.getRuntime().exec() in Ubuntu

Hey :)

a few days ago I needed to run `/etc/init.d/networking restart` command by Runtime.getRuntime().exec() in Java EE web application. The first and easiest way that came to mind was sudo without password and... It Worked!
* To execute sudo without password, open /etc/sudoers by text editor like `nano`:
[bash]
$ sudo nano /etc/sudoers
[/bash]
And add your user or group to the end of file like below:
[shell]
# for user
USER_NAME ALL= NOPASSWD: ALL

# for group
%GROUP_NAME ALL= NOPASSWD: ALL
[/shell]

let's see my Java code:
[java]
String command = "sudo /etc/init.d/networking restart";
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(command);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
[/java]

Troubleshooting
if you get `sudo: no tty present and no askpass program specified` error, make sure the user that runs command is in /etc/sudoers.

let me know if you find similar or easier way :)

4 comments:

  1. Using UBUNTU 10.10

    Before editing sudoers, I had to chmod +w.

    Immediately after the chmod command, the sudo command failed.

    sudo: /etc/sudoers is mode 0640, should be 0440
    sudo: no valid sudoers sources found, quitting

    Now, I cannot do anything, and I may have to re-install Ubuntu.

    Thanks alot.

    ReplyDelete
  2. You can fix it:
    http://www.nathandrew.org/2009/07/11/fix-sudoers-permissions-without-reboot/

    OR

    http://psychocats.net/ubuntu/fixsudo

    ReplyDelete
  3. The solution is not really working for me.

    re @ Troubleshooting
    if you get `sudo: no tty present and no askpass program specified` error, make sure the user that runs command is in /etc/sudoers.

    As far as you runtime.exec(command) typing "sudo" in front of the command, the user executing that is actually "root". So, yes ofcourse, the user is in /etc/sudoers, but in my case still an error occurs:
    sudo: no tty present and no askpass program specified


    Interesting that it worked for you.

    ReplyDelete
  4. Hi,

    I found another option, for me is more clean. I use gksudo, because if you want share your application, you dont need change your enviroment and your application is more portable.

    Greetings!!

    ReplyDelete