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 :)