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')
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.
在尝试了模块
os
、subprocess
、getpass
之后,我意识到问题不在于是否设置了用户。使用os.setuid
设置或更改用户,但是,模块中获取用户名的方法(如os.getlogin()
,getpass.getuser()
)实际上无法正确获取用户名。如果使用subprocess.Popen()
或os.system()
运行shell命令whoami
或id
,则将获得更改的用户。这些对我来说是一个小小的困惑。下面的脚本显示了所有这些奇怪的行为。getpass.getuser()
不使用getuid()
或geteuid()
获取当前用户。http://docs.python.org/3/library/getpass.html#getpass.getuser
相关问题 更多 >
编程相关推荐