os.setuid不会改变当前的美国

2024-04-29 05:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改当前用户以执行脚本。我做到了

import os
newuid = pwd.getpwnam('newuser').pw_uid
os.setuid(newuid)    
print('User :' + getpass.getuser());

我仍然在得到root。有比这更好的办法吗?我希望切换用户一次,然后用新用户继续脚本中的其余命令执行。


Tags: 用户import脚本uidospwdprintpw
2条回答

在尝试了模块ossubprocessgetpass之后,我意识到问题不在于是否设置了用户。使用os.setuid设置或更改用户,但是,模块中获取用户名的方法(如os.getlogin()getpass.getuser())实际上无法正确获取用户名。如果使用subprocess.Popen()os.system()运行shell命令whoamiid,则将获得更改的用户。这些对我来说是一个小小的困惑。下面的脚本显示了所有这些奇怪的行为。

import os
import subprocess
import pwd
import getpass

#os.chdir("/tmp")

#uid = pwd.getpwnam('newuser').pw_uid

os.setuid(500)     # newuser's id found from shell cmd line

print os.getuid()

p = subprocess.Popen(['id'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = p.communicate()

# print os.system('useradd newuser1') # Try this commenting, it will not create, and then  try commenting above line of setuid. i.e. it will become root, and then see the change.

# print os.getcwd()

print out,err

p = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = p.communicate()

print out,err

print getpass.getuser()

print os.getlogin()

print os.system('whoami')

getpass.getuser()不使用getuid()geteuid()获取当前用户。

http://docs.python.org/3/library/getpass.html#getpass.getuser

This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the pwd module, otherwise, an exception is raised.

相关问题 更多 >