I try to launch a command from Java in Linux with sudo
and I can't find a way. I have tried the following, but... although from the terminal it works, from the execution of my program it does not.
public Boolean activarServicio(){
lanzarComando();
Boolean finaly = false;
try{
if(!estado){
consola2=Terminal.lanzarComando("teamviewer --daemon enable");
//consola2=Terminal.lanzarComando("echo mipassword | sudo -S teamviewer --daemon enable");
finaly = true;
}
}catch(IOException err){
}
return finaly;
}
Does anyone have any idea how to solve this?
On English SO there are two solutions to an equivalent question :
The first, simple but highly discouraged because it exposes the password, is the following:
The second, safer, is to edit
/etc/sudoers
withvisudo
and give your user NOPASSWD permission to a specific script that performs the task you need:Take a look at the class
Runtime
, specifically its methodexec()
.Note that Runtime is a class of type Singleton, so to use it you must use the static method
getRuntime()
.As an example:
It will open my text editor.