Akshay Akshay - 5 months ago 21
Python Question

How to get sudo username in python?

I am trying to run my script as below and want access to sudo user running this script.

:$sudo -u usergroup script.py

So here I am expecting 'usergroup' as output.
What I have tried is,

  • getpass: This gives you the actual user and not sudo user


:$ sudo -u usergroup ipython

In [1]: import getpass

In [2]: getpass.getuser()
Out[2]: 'akshay'

  • os.getenv


In [4]: os.getenv("SUDO_USER")
Out[4]: 'akshay'

In [5]: os.getenv("USER")
Out[5]: 'akshay'

I am using below python version.

In [7]: sys.version
Out[7]: '2.7.11 (default, Apr 25 2016, 09:27:56) \n[GCC 5.2.1 20150902 (Red Hat 5.2.1-2)]'

In [8]:

Kindly help here. Could not came across any existing question or solution for it.

Answer Source

You need to use os.geteuid to get effective user id (euid, used for most access checks).

>>> import os
>>> os.geteuid()

Then, pass the return value to pwd.getpwuid to get information about the uid returned:

>>> import pwd
>>> pwd.getpwuid(os.geteuid())
pwd.struct_passwd(pw_name='root', pw_passwd='x', ...)

Access pw_name attribute (or [0]) of the pwd.getpwuid() to get username of the effective user.

>>> pwd.getpwuid(os.geteuid()).pw_name
>>> pwd.getpwuid(os.geteuid())[0]

To get effective group information, use os.getegid + grp.getgrgid.

>>> grp.getgrgid(os.getegid())
grp.struct_group(gr_name='root', gr_passwd='x', gr_gid=0, gr_mem=[])
>>> grp.getgrgid(os.getegid()).gr_name