Search code examples
pythonlinuxsudoprivileges

What is a pythonic way of running a Python routine as another user (e.g. root)?


In the spirit of this answer ("Don't call shell commands from Python. You can do everything in Python that shell commands can."), which is rather common advise given to many people, how do I run a selected individual routine (and ONLY this routine) within a Python program as another user, e.g. root, in a pythonic (and somewhat secure) manner?

For example, I have a routine like this in some code:

import os
import signal
import subprocess

def kill_proc(pid, k_signal = signal.SIGINT, sudo = False):
    if sudo:
        subprocess.Popen(['sudo', 'kill', '-%d' % k_signal, '%d' % pid]).wait()
    else:
        os.kill(pid, k_signal)

If I do not need to be root, I can just call os.kill(pid, k_signal) in this example. However, if I need super user privileges for sending a signal in my example, I must send the signal though a command in a subprocess. How could I use os.kill instead?


Solution

  • You cannot run a Python function as another user.

    A Unix-like OS associates each process with a particular user. One cannot reassign a process to a different user unless the original owner was root to begin with. A Python function is not a process and cannot have its own user.