简体   繁体   English

os.setuid不会更改当前用户

[英]os.setuid doesn't change current user

I wanted to change current user for script execution. 我想更改当前用户的脚本执行。 I did this 我这样做了

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

I am still getting root . 我还在root Is there better way than this? 还有比这更好的方法吗? I want switch user once and then continue rest of the commands execution in the script with that new user. 我希望切换用户一次,然后继续使用该新用户在脚本中执行其余的命令。

getpass.getuser() doesn't use getuid() or geteuid() to get the current user. getpass.getuser()不使用getuid()geteuid()来获取当前用户。

http://docs.python.org/3/library/getpass.html#getpass.getuser 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. 此函数按顺序检查环境变量LOGNAME,USER,LNAME和USERNAME,并返回设置为非空字符串的第一个值。 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. 如果未设置,则在支持pwd模块的系统上返回密码数据库的登录名,否则将引发异常。

After trying modules os , subprocess , getpass , I realised that the problem is not whether the user is set. 在尝试了模块ossubprocessgetpass ,我意识到问题不在于用户是否已设置。 The user gets set or gets changed using os.setuid , however, the methods from modules to get username like os.getlogin() , getpass.getuser() , actually does not get username properly. 用户使用os.setuid进行设置或更改,但是,模块中获取用户名的方法os.getlogin()os.getlogin()getpass.getuser()实际上无法正确获取用户名。 If you run a shell command whoami or id using subprocess.Popen() or os.system() , you will get the changed user. 如果你运行一个shell命令whoamiid使用subprocess.Popen()os.system()您将得到改变的用户。 These are little puzzled outputs for me. 对我来说这些都是一些困惑的输出。 Below is script which shows all these weird behaviours. 下面是显示所有这些奇怪行为的脚本。

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

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

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