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`:
$ sudo nano /etc/sudoers
And add your user or group to the end of file like below:
# for user USER_NAME ALL= NOPASSWD: ALL # for group %GROUP_NAME ALL= NOPASSWD: ALL
let’s see my Java code:
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();
}
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 ![]()


