2

I would like to redirect (switch) one execution to other user instead root while using sudo.

Example: sudo startup.sh will execute the startup.sh as root, but what is needed is for it to be executed as another user, say tomcat.

Just for this particular execution I just want them to execute the way they are using, i.e., sudo startup.sh, but in the background (under the hood) I want that to be changed to sudo su - tomcat startup.sh as I can't tell the users not to use sudo -su or sudo -u.

How can I achieve this?

2

2 Answers 2

5

You can't easily do what you ask (i.e. make sudo startup.sh run as a named non-root user). What you can do, though, is one or both of the following

  1. Tell users to use sudo -u tomcat /path/to/startup.sh instead of sudo /path/to/startup.sh, and disallow the latter anyway

    Add this line to your sudoers (remember visudo) such that tomcat here is the target user account. Change the first ALL to a list of users if there are only certain people allowed to run the script as the target user

     ALL ALL=(tomcat) /path/to/startup.sh 
  2. Make the script perform the sudo, and disallow sudo -u root for the script. You'll need #1 (above). Ensure that tomcat here matches the tomcat in sudoers.

     #!/bin/bash # targetUser=tomcat if [[ $UID -ne "$(id -u "$targetUser")" ]] then exec sudo -u "$targetUser" "$0" "$@" exit 1 fi # ...script continues but as the $targetUser... 

    This allows people to run /path/to/startup.sh (or even just startup.sh if it's in the $PATH) and not worry about the sudo part.

0
2

You can use sudo with a -u switch.

Example:

sudo -u tomcat whoami 
2
  • Well just for this particular execution i just want them to execute the way they are using i.e. sudo startup.sh but in the background i want that to be changed to sudo su - tomcat startup.sh as i can't inform the users not to use sudo -su or sudo -u Commented Jul 13, 2020 at 17:53
  • 1
    I'd just add 'tomcat ALL=/usr/bin/startup.sh' (change /usr/bin/ to where ever your script is located) to /etc/sudoers. Commented Jul 13, 2020 at 22:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.