Running a .py script as root. This script has two functions:
def func(): ... def func2(): ...
There are two users in the system: user and user2. How to run funcas user userand accordingly func2as user user2. Given that the script is running under root?
Answer # 1
The classic *nix solution for such cases is:
fork()descendant ⇒ privilege downgrade ⇒ function launch.
In python it would look something like this:
import os, pwd, sys def runAs(user, func): uid= pwd.getpwnam(user).pw_uid # get uid by name pid= os.fork() # fork if pid== 0: # child try: os.setuid(uid) # change user func() # run function except: # exit with an error if something went wrong sys.exit(os.EX_SOFTWARE) else: # proper completion sys.exit(os.EX_OK) # no return else: # parent return pid pid1= runAs('user1', func) # waiting for children to finish work (if necessary) (pid,rc)= os.waitpid(pid1, 0) if rc != os.EX_OK: print("Child exited with an error code")
It should be borne in mind that the function in this case will work in a separate process with all the pluses and minuses.