24

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?

2
  • 1
    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). Commented Apr 16, 2011 at 18:54
  • Thank you for the advice. Ok, I will set my euid to SUDO_UID.
    – rubik
    Commented Apr 17, 2011 at 7:49

2 Answers 2

39

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

2
  • 3
    +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
    Commented Apr 16, 2011 at 18:46
  • 4
    SUDO_USER was exactly what I was looking for.
    – johnthagen
    Commented Aug 29, 2019 at 11:51
2

This is what I currently use for covering systemd (="root"), sudo, pkexec and normal execution. Could be made more beautiful for sure:

import os
import getpass
import pwd

def get_user():
    """Try to find the user who called sudo/pkexec."""
    try:
        return os.getlogin()
    except OSError:
        # failed in some ubuntu installations and in systemd services
        pass

    try:
        user = os.environ['USER']
    except KeyError:
        # possibly a systemd service. no sudo was used
        return getpass.getuser()

    if user == 'root':
        try:
            return os.environ['SUDO_USER']
        except KeyError:
            # no sudo was used
            pass

        try:
            pkexec_uid = int(os.environ['PKEXEC_UID'])
            return pwd.getpwuid(pkexec_uid).pw_name
        except KeyError:
            # no pkexec was used
            pass

    return user
➜  ~ python3 /home/mango/getuser.py
mango
➜  ~ sudo python3 /home/mango/getuser.py
mango
➜  ~ pkexec python3 /home/mango/getuser.py
mango

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .