1

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?

s-m-e
  • 3,433
  • 2
  • 34
  • 71
  • 2
    The answer you are quoting is a sweeping overgeneralisation. Don't give it much weight. What is a "shell command" anyway? If `cp` is one, why not `firefox`? – n. m. could be an AI Dec 19 '17 at 17:19
  • @n.m. I am aware of the overgeneralisation ;) Though, I have to admit that I am nevertheless interested to see whether there is an answer to this or not. – s-m-e Dec 19 '17 at 17:24

1 Answers1

1

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • 2
    The least you must always do then is to spin up another process, which is somehow associated with the right user. Which begs the question whether there is a "pythonic abstraction" through e.g. modules like ``multiprocessing`` which would make this thing look like a normal function call ... *(I am well aware that this could easily become bizarre - firing up another Python interpreter process like ``multiprocessing`` does just for calling a small method like in my example.)* – s-m-e Dec 19 '17 at 17:42