Linux – sudo to run command as different user


I am trying to setup a script that will be run as a "maint" user. The script is basically a menu that allows maintenance personnel to do different things on the server.
However, some of the scripts that the maint menu will execute must be run as particular users in order to work properly.

my question is how do I execute said commands with sudo and requiring no password. Remember, the scripts that get executing from within the menu must actually be run as a different user. Here is a demo of what I have tried and am trying to accomplish.

file "sudoTest" lives in /home/user1/
file "testSudo" lives in /home/maint

"sudoTest" looks like this currently:


echo "I am in sudoTest"

"testSudo" looks like this currently:


sudo -u user1 /home/user1/sudoTest

My goal is basically that when I am logged in as user maint and run "testSudo", the output of the whoami command will be "user1"

This is what the file looks like currently when i use the visudo command

# This file MUST be edited with the 'visudo' command as root.
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
# See the man page for details on how to write a sudoers file.
Defaults        env_reset
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL= NOPASSWD: /home/user1/*

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d        

The other strange thing is that when i do this from command line:

sudo /home/user1/sudoTest

It allows me to run the script and i get the output:

I am in sudoTest

but when i try to execute "testSudo" it asks for password, and when i enter it i get back:

Sorry, user maint is not allowed to execute '/home/user1/testSudo' as user1

Thanks for any help!

Best Answer

I have found the issue.

The problem was that the sudoers file was missing a piece

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL= NOPASSWD: /home/user1/*

should be

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL=(ALL) NOPASSWD: /home/user1/*
Related Question