4

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.

4
  • Are you trying to execute commands on the server as sudo? or just getting information about sudo? Commented May 12, 2017 at 5:14
  • just getting information for logging. Commented May 12, 2017 at 5:16
  • Don't know what's your question, the code works well. Commented May 12, 2017 at 5:19
  • 1
    sudo expands to switch user and do. It can be used to execute a command as any other user. The user can be specified using -u. Now the default (in case -u is not provided) is root. Commented May 12, 2017 at 5:26

1 Answer 1

9

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

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

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
'root'
>>> pwd.getpwuid(os.geteuid())[0]
'root'

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
'root'
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect solution for my usecase, infact later one liner pwd.getpwuid(os.geteuid()).pw_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.