How to get the name of the user that launched `sudo`
8,803
When you fire off something with sudo
a couple of environment variables get set, specifically I think you are looking for SUDO_UID
. These should be accessible to any program running through the usual channels of accessing environment variables.
You can see the other things set by cheating like this from a shell: sudo env | grep SUDO
Related videos on Youtube
Author by
rubik
Updated on September 18, 2022Comments
-
rubik over 1 year
My problem: I have a Python program, and the user launch it using
sudo
. Sometimes I have to get the user's home, and I can do this only knowing its name:import pwd pwd.getpwnam(username)
So: how can I get the name of the user that launched the program?
-
Admin about 13 yearsInder most configurations,
sudo
leaves theHOME
environment variable intact (this can be overridden at compile- or run-time). But you may or may not be able to use the environment variable, depending on what you want to happen if the user specifies a different value forHOME
(what if bob runsHOME=/home/joe sudo your_script
?). You should probably set your euid to the calling user (given bySUDO_UID
) before making any filesystem access (apart from whatever actually requires root permission in your script). -
Admin about 13 yearsThank you for the advice. Ok, I will set my
euid
toSUDO_UID
.
-
-
rubik about 13 years+1 WoW! Thank you very much! That was exactly what I was looking for. I think I will use
SUDO_UID
andSUDO_USER
. Thank you again. -
phoenix over 4 years
SUDO_USER
was exactly what I was looking for.