Get parent user after sudo with Python

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?


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.


在大多数情况下,SUDO_USER环境变量应该可用:

import os

if os.environ.has_key('SUDO_USER'):
    print os.environ['SUDO_USER']
else:
    print os.environ['USER']

如前所述,您可以使用getpass模块

>>> import getpass
>>> getpass.getuser()
'kostya'
链接地址: http://www.djcxy.com/p/79436.html

上一篇: 在后台运行命令

下一篇: 在使用Python完成sudo之后获取父级用户