Launch commands from Java

3

I try to launch a command in Linux with Java with sudo and I can not find the way. I tried the following, but ... even though from the terminal it works, since 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?

    
asked by Víctor 30.08.2017 в 21:54
source

2 answers

4

In SO in English there are two solutions to one Equivalent question :

The first, simple but very discouraged because it exposes the password, is as follows:

public static void main(String[] args) throws IOException {

    String[] cmd = {"/bin/bash","-c","echo password| sudo -S ls"};
    Process pb = Runtime.getRuntime().exec(cmd);

    String line;
    BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
    while ((line = input.readLine()) != null) {
        System.out.println(line);
    }
    input.close();
}

The second, more secure, is to edit /etc/sudoers with visudo and give your user NOPASSWD permission for a specific script that performs the task you need:

nombre_de_usuario ALL=(ALL) NOPASSWD: /opt/mi-script.sh
    
answered by 31.08.2017 / 09:54
source
1

Take a look at the class Runtime , in concrete, its method exec() .

Notice that Runtime is a class of type Singleton, so to use it you should use the static method getRuntime() .

As an example:

try {
    Runtime.getRuntime().exec("D:\mi_ruta_hacia_atom\atom");
} catch(IOException e) {
    System.out.println("EXCEPTION: " + e.getMessage());
}

It will open my text editor.

    
answered by 31.08.2017 в 09:23