0

I am writing a program in python, which is run as root (with sudo) and I am trying to get the username of the session it was run in. I tried with os.getuid() combined with the pwd module but it returns root. I thought of getting the uid of the grandfather process (program -> sudo -> program with the right uid), but I think this is not an elegant solution, and it doesn't work in all cases. How to get the username (or uid) of the current session ?

PS: I am not English so there may be some mistakes in my message

Rayzeq
  • 25
  • 2
  • 6

1 Answers1

1

The simplest way to do this on UNIX OS's is by using the "SUDO_USER" environment variable:

>>> import os
>>> os.getenv("SUDO_USER")
'test_user'

The only caveat is that this is not truly portable, for example on Fedora 17 this variable is not set (But will work for almost all environments and distros).


There is an alternative much more bulky solution that covers much more edge cases, this might work better for your use case.

import os
import shutil
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

EG of working cases:

$ python3 getuser.py
test_user
$ sudo python3 getuser.py
test_user
$ pkexec python3 getuser.py
test_user
Fallstop
  • 26
  • 1