Search code examples
pythoninterpreterinterprocess

Is it possible to pass a callable programmatically to a python instance (invoked with different permissions)


Assume I have python code

def my_great_func(an_arg):
  a_file = open("/user/or/root/file", "w")
  a_file.write("bla")

which I want to maintain without paying attention to invokation with and without priveleges. At the same time I don't want to invoke the script with sudo/enforce the invokation with sudo (although this would be a legitemate pratice) or enable setuid for my python interpreter (generally a bad idea...). An idea is now to start a second instance of the python interpretor and communicate over processes/pipes. In order to maximize the maintainability of the code it would be nice to simply pass the callable to the instance (e.g. started with subprocess.Popen and addressed to with its PID) like I would pass it to multiprocess.Process (which I can't use because I can't setuid in the subprocess). I imagine something like

# please consider this pseudo python code
pid = subprocess.Popen(["sudo", "python"]).get_pid()
thelib.pass_callable(pid, target, args)

or even

interpreter_instance = greatlib.Python(target, args)
interpreter_instance.start()
interpreter_instance.wait()

Is that possible and covered by existing libs?


Solution

  • Generally speaking, you don't want any script to run as Super User unless the script invoking it was called with Super User. This is not only an issue of good practice and secure programming, but also programmer etiquette. If any part of your program requires use of Super User, this intention should be made known before you even begin the program.

    With that in mind, the Python thread library should work just fine for this.