Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent user after sudo with Python

Tags:

python

unix

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?

like image 441
James Avatar asked Jul 01 '14 18:07

James


2 Answers

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']
like image 78
bcicen Avatar answered Sep 26 '22 02:09

bcicen


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.

like image 25
Martin Tournoij Avatar answered Sep 25 '22 02:09

Martin Tournoij