Home>

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?

The essence of the question is not clear. The program is launched from some user, and inherits his rights. A part of a program cannot be executed by one user and another by another. But in the program, you can run a child process from another user through sudo. What you want -it is not clear why, and how

Total Pusher2022-02-12 20:54:13

Perhaps you need it -the essence is the same, launching an instance from another user.

Total Pusher2022-02-12 20:54:13
  • 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.

    This is too low level for Python. There is a special processing module or something like that, you need to use it.

    0andriy2022-02-12 20:54:13

    @0andriy and it even has privilege downgrading?

    Fat-Zer2022-02-12 20:54:13