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?
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With