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

Share:
8,803

Related videos on Youtube

rubik
Author by

rubik

Updated on September 18, 2022

Comments

  • rubik
    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
      Admin about 13 years
      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).
    • Admin
      Admin about 13 years
      Thank you for the advice. Ok, I will set my euid to SUDO_UID.
  • rubik
    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 and SUDO_USER. Thank you again.
  • phoenix
    phoenix over 4 years
    SUDO_USER was exactly what I was looking for.