Linux - How to execute a command as another user, Run a script or command as another user

How to execute a command as another user


Some time there might be a requirement that a user have to execute a command or a script as another user. In such situation you can use visudo to give sudo access to the particula user or multiple user. Add the below entry in /etc/sudoers file.

visudo
# user1 ALL=(user2)  NOPASSWD: /usr/bin/crontab
In the above example the user1 can run only crontab command as user2. It will also be very restrictive, as in user1 can only run crontab command under user2 and nothing else.

To provide access to multiple users you can use the below command
# you ALL=(user1,user2,user3,user4)  NOPASSWD: /usr/bin/crontab
In the above example the user you can run only crontab command as user1,user2,user3 and user4.

The same way you can provide the access to execute or run the scripts too.
# user1 ALL=(user2)  NOPASSWD: /home/user2/shell-scripts/myscript.sh

After making the above settings now the user1 can execute the command as below
[user1 ~]# sudo -u user2 crontab -l

[user1 ~]# sudo -u user2 crontab -e 

The topic on Linux - How to execute a command as another user is posted by - Math

Hope you have enjoyed, Linux - How to execute a command as another userThanks for your time

Tech Bluff