简体   繁体   English

使用Python在sudo之后获取父用户

[英]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: 我希望在Python中使用sudo命令后获取用户。例如,从shell我可以做到:

# 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? 如何在不使用外部程序的情况下在Python中执行此操作?

SUDO_USER environmental variable should be available in most cases: 在大多数情况下,应该提供SUDO_USER环境变量:

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) ; who am iutmp(5)获得了它的信息utmp(5) ; with Python you can access with information with pyutmp ; 使用Python,您可以使用pyutmp访问信息;

Here's an example, adapted from the pyutmp homepage: 这是一个例子,改编自pyutmp主页:

#!/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). 缺点:这是一个C模块(即需要编译),只适用于Python 2(而不是3)。

Perhaps a better alternative is using of the environment variables that sudo offers? 也许更好的选择是使用sudo提供的环境变量? 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. 所以使用像os.environ['SUDO_USER']这样的东西可能会更好,这取决于你正在尝试做什么。

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. 应该在su之前返回原始用户。

import os
print os.environ["USER"]

这是一个可以做到的单线程。

user = os.environ['SUDO_USER'] if 'SUDO_USER' in os.environ else os.environ['USER']

Either os.getlogin() or os.getenv('SUDO_USER') look like good choices. os.getlogin()os.getenv('SUDO_USER')看起来都是不错的选择。

[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'

as referenced before , you can use getpass module 如前所述 ,您可以使用getpass模块

>>> import getpass
>>> getpass.getuser()
'kostya'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM