How to Find the Original User Through Multiple Sudo and Su Commands

How do you find the original user through multiple sudo and su commands?

Results:

Use who am i | awk '{print $1}' OR logname as no other methods are guaranteed.

Logged in as self:

evan> echo $USER
evan
evan> echo $SUDO_USER

evan> echo $LOGNAME
evan
evan> whoami
evan
evan> who am i | awk '{print $1}'
evan
evan> logname
evan
evan>

Normal sudo:

evan> sudo -s
root> echo $USER
root
root> echo $SUDO_USER
evan
root> echo $LOGNAME
root
root> whoami
root
root> who am i | awk '{print $1}'
evan
root> logname
evan
root>

sudo su - :

evan> sudo su -
[root ]# echo $USER
root
[root ]# echo $SUDO_USER

[root ]# echo $LOGNAME
root
[root ]# whoami
root
[root ]# who am i | awk '{print $1}'
evan
[root ]# logname
evan
[root ]#

sudo su -; su tom :

evan> sudo su -
[root ]# su tom
tom$ echo $USER
tom
tom$ echo $SUDO_USER

tom$ echo $LOGNAME
tom
tom$ whoami
tom
tom$ who am i | awk '{print $1}'
evan
tom$ logname
evan
tom$

Can I find which user used sudo to run my script?

You could check if there are some environment variables set by sudo:

set | grep SUDO

Output:

SUDO_COMMAND=/bin/bash
SUDO_GID=1000
SUDO_UID=1000
SUDO_USER=user1

How to run multiple commands while using sudo as another user

Bash supports a -c flag that lets you specify the command to run as a command-line argument — basically an inline Bash script. That means you can easily combine multiple commands into a single call to bash, which is then easily sudo-ed:

sudo -i -u john.smith bash -c 'whoami ; cd /tmp/ ; ls -ltr'

or

sudo -i -u john.smith \
bash -c ' whoami
cd /tmp/
ls -ltr
'

(Other shell languages have the same feature.)

root undoing previous changes after sudo su user

The problem you're having, is that ~ resolves to the home directory for the current user. So when logged in as root, ~ points to root's home directory (usually at /root), whereas for myuser, ~ points at myuser's home directory (usually /home/myuser), so you're actually editing different files.

Switching back to previous user after sudo -i using Bash

sudo -i is for interactive use, to run a simple command as root, you just add sudo in front of it. In this case, since we want to pipe to a file that requires elevated permissions, we should run the shell as sudo. The commands in the questions could be written as:

...
sudo bash -c 'echo "www-data ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers'
...


Related Topics



Leave a reply



Submit