Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


So: how can I get the name of the user that launched the program?

share|improve this question
Inder most configurations, sudo leaves the HOME 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 for HOME (what if bob runs HOME=/home/joe sudo your_script?). You should probably set your euid to the calling user (given by SUDO_UID) before making any filesystem access (apart from whatever actually requires root permission in your script). – Gilles Apr 16 '11 at 18:54
Thank you for the advice. Ok, I will set my euid to SUDO_UID. – rubik Apr 17 '11 at 7:49
up vote 12 down vote accepted

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

share|improve this answer
+1 WoW! Thank you very much! That was exactly what I was looking for. I think I will use SUDO_UID and SUDO_USER. Thank you again. – rubik Apr 16 '11 at 18:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.