Os.setuid does not change the current user

I want to change the current user to execute a script. I did it

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

I am still getting root . Is there a better way than this? I want the user to switch once, and then continue to execute commands in the script with this new user.

+6
source share
2 answers

getpass.getuser() does not use getuid() or geteuid() to get the current user.

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

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

+5
source

After testing the os , subprocess , getpass modules, I realized that the problem is not whether the user is installed. The user gets the set or changes with os.setuid , however methods from the modules to get the username, such as os.getlogin() , getpass.getuser() , do not actually get the username properly. If you run the whoami or id shell whoami using subprocess.Popen() or os.system() , you will get a modified user. For me this is a little puzzling. Below is a script that shows all these strange behaviors.

 import os import subprocess import pwd import getpass #os.chdir("/tmp") #uid = pwd.getpwnam('newuser').pw_uid os.setuid(500) # newuser 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. ie 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') 
+1
source

Source: https://habr.com/ru/post/954174/


All Articles