LLI Wiki — My Digital Knowledge Base

Run commands as another user and configure passwordless sudo

Using sudo and su to switch users, and configuring NOPASSWD in sudoers.

How to run a command as another user (or as root) with sudo and su, and how to configure passwordless sudo.

Run a command as another user

# login-style run without the user's shell, as user "appuser"
sudo su -s /bin/bash -c 'whoami' appuser

# simple command as another user
sudo -u appuser /usr/bin/php -f /path/to/script.php

# with an explicit shell
sudo su -c "echo 'test'" -s /bin/sh appuser
sudo su -c "less /etc/my.cnf" -s /bin/sh mysql

Switch user

$ whoami
user1
$ su - user2        # asks for user2's password
$ whoami
user2
$ exit

To become root, no user name is needed:

$ su -

With sudo:

sudo -i     # interactive root login shell
sudo -s     # root shell using the current user's shell
echo <password> | sudo -S <command>

The password ends up in the shell history and process list; prefer the configuration below.

Passwordless sudo

Restrict it to specific commands with visudo (or sudo vim /etc/sudoers):

User_Alias USERS = your_user
Cmnd_Alias CMDS = /usr/bin/make
USERS ALL = (ALL) NOPASSWD: CMDS

Or grant it for all commands to a user through a drop-in file (do not use a .conf extension, files containing a dot are ignored in /etc/sudoers.d):

su -
echo -e "appuser\tALL=(ALL)\tNOPASSWD: ALL" > /etc/sudoers.d/020_sudo_appuser
cat /etc/sudoers.d/020_sudo_appuser
appuser ALL=(ALL) NOPASSWD: ALL

Notes

Mastodon LLIMastodon SocialFosstodon