Skip to content
Advertisement

Cannot execute command as another user with sudo

I have this code, that is running on tomcat:

try {
    Process p = Runtime.getRuntime().exec("sh /home/user/script.sh");
    p.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    StringBuilder result = new StringBuilder();
    String line = "";
    while ((line = reader.readLine()) != null) {
        result.append(line).append('n');
    }

    while ((line = errorReader.readLine()) != null) {
        System.err.println(line);
    }
    return result.toString();
} catch (IOException | InterruptedException e) {
    System.err.println(e.getMessage());
}

And my script.sh file:

#/bin/sh
echo 'USER_PASSWORD'| sudo -S -u USER ls

From command line, the script is executed excellent and I see results.

But when executing it from tomcat I get this message:

[sudo] password for tomcat: Sorry, try again.
[sudo] password for tomcat:
sudo: 1 incorrect password attempt

I cannot solve this problem. I need your help.

P.S: Sorry me for bad english. Thanks!

Advertisement

Answer

I guess that the problem occurs because the Tomcat process is running with a different user (with different permissions) than the one you are using to execute the commands manually.

Usually, the tomcat user is named “tomcat” or something like “tomcat7”, “tomcat8” etc. depending on the version.

To solve your problem, you have to add sudo rights for your tomcat user.

If you don’t know the exact name of your tomcat user, you can check it with following command in the terminal while tomcat is running:

ps aux | grep -v grep | grep tomcat

which will return something like this:

tomcat9 26840 1.4 49.1 7920356 1904504 ? Sl Apr26 201:44 /usr/lib/jvm/java/bin/java…

as you can see, the name of the tomcat user will be in the first column of the displayed output.

Then, you add the sudo rights for this user and enable using sudo without requiring password by adding the following line into the file “/etc/sudoers” (you can edit it by entering “sudo visudo” in the terminal, this is some kind of shortcut for editing this file)

tomcat9 ALL=(ALL) NOPASSWD: ALL

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement