5

I would like to get the parent user after a sudo command in Python For example, from the shell I can do:

# Shows root; *undesired* output
$ sudo whoami
root

# Shows parent user sjcipher, desired output
$ sudo who am i
sjcipher

How do I do this in Python without using an external program?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
James Sapam
  • 16,036
  • 12
  • 50
  • 73

6 Answers6

8

SUDO_USER environmental variable should be available in most cases:

import os

if os.environ.has_key('SUDO_USER'):
    print os.environ['SUDO_USER']
else:
    print os.environ['USER']
bcicen
  • 81
  • 1
  • 1
3

who am i gets it's information from utmp(5); with Python you can access with information with pyutmp;

Here's an example, adapted from the pyutmp homepage:

#!/usr/bin/env python2

from pyutmp import UtmpFile
import time, os

mytty = os.ttyname(os.open("/dev/stdin", os.O_RDONLY))

for utmp in UtmpFile():
    if utmp.ut_user_process and utmp.ut_line == mytty:
        print '%s logged in at %s on tty %s' % (utmp.ut_user, time.ctime(utmp.ut_time), utmp.ut_line)


$ ./test.py
martin logged in at Tue Jul  1 21:38:35 2014 on tty /dev/pts/5

$ sudo ./test.py
martin logged in at Tue Jul  1 21:38:35 2014 on tty /dev/pts/5

Drawbacks: this is a C module (ie. it requires compiling), and only works with Python 2 (not 3).

Perhaps a better alternative is using of the environment variables that sudo offers? For example:

[~]% sudo env | grep 1001
SUDO_UID=1001
SUDO_GID=1001

[~]% sudo env | grep martin
SUDO_USER=martin

So using something like os.environ['SUDO_USER'] may be better, depending on what you're exactly trying to do.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
0

Depending on the setup you could use the environment variables that have been set. Note, that this may not work in all cases but may in yours. Should return the original user before su.

import os
print os.environ["USER"]
Bob
  • 684
  • 4
  • 4
0

Here's a one-liner that will do it.

user = os.environ['SUDO_USER'] if 'SUDO_USER' in os.environ else os.environ['USER']
Clay Risser
  • 3,272
  • 1
  • 25
  • 28
0

Either os.getlogin() or os.getenv('SUDO_USER') look like good choices.

[vagrant@localhost ~]$ sudo python3.6
Python 3.6.3 (default, Oct 11 2017, 18:17:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getlogin()
'vagrant'
>>> os.getenv('SUDO_USER')
'vagrant'
>>> os.getenv('USER')
'root'
>>> import getpass
>>> getpass.getuser()
'root'
Eric Smith
  • 2,739
  • 2
  • 30
  • 29
-1

as referenced before, you can use getpass module

>>> import getpass
>>> getpass.getuser()
'kostya'
Community
  • 1
  • 1
Mirat Can Bayrak
  • 631
  • 7
  • 18