How to Allow a User to Run Commands as Another User in Ubuntu
Managing user privileges is essential for system administration in Ubuntu. This article details the methods for permitting one user to execute commands under the identity of another. We will explore the standard switch user command, the sudo utility, and how to safely modify configuration files to grant persistent permissions.
Using the su Command
The su (switch user) command allows you to log in as
another user directly. You must know the password of the target account.
To switch to a user named “exampleuser” and load their environment
variables, run:
su - exampleuserTo exit the session and return to your original user, type
exit.
Using sudo to Execute Specific Commands
The sudo command allows authorized users to run specific
commands as another user without switching the entire shell session. You
will be prompted for your own password, not the target user’s password.
The syntax is:
sudo -u exampleuser commandFor example, to list the home directory contents as “exampleuser”:
sudo -u exampleuser ls /home/exampleuserConfiguring Permanent Sudoers Access
To allow a user to run commands as another user repeatedly without
editing command lines manually, you must configure the sudoers file.
Always use the visudo command to edit this file, as it
checks for syntax errors before saving.
Open the sudoers file:
sudo visudoAdd a rule granting permission. To allow “adminuser” to run commands as “exampleuser”, add this line:
adminuser ALL=(exampleuser) ALLSave and exit the editor.
Once configured, “adminuser” can run any command as “exampleuser”
using the sudo -u exampleuser syntax described earlier.