Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: sudo context manager?

Is there any possible way to implement a sudo context manager which runs the enclosing scope as another user, using the sudoers system?

system('whoami')  # same result as echo $USER
with sudo():
    system('whoami')  # root

I doubt that the sudo(8) executable will help me here, but maybe there is some C-level interface that I can bind to?


Motivation: I can almost port this shell script entirely to python without even any subprocesses, except I currently have to system('sudo sh -c "echo %i > /dev/thatfile"' % value). It would be so elegant if I could with sudo(), open('/dev/thatfile', 'w') as thatfile: thatfile.write(str(value)).

like image 328
bukzor Avatar asked Mar 12 '14 07:03

bukzor


1 Answers

I suspect this is not possible in any simple way. Programs that escalate their permissions like sudo must have a flag set in their file system permissions (the is the "setuid" bit) in order to tell the operating system to run them as a different user than the one that started them up. Unless you want your whole Python interpreter to be setuid root, there's no direct way to do something equivalent for just some small part of your Python code.

It might conceivably be possible to implement a sudo style context manager not by making your regular Python code run privileged, but rather by temporarily replacing the library code that makes various OS calls (such as opening a file) with some kind of proxy that connects it to a setuid helper program. But it would be a lot of work to get something like that to work, and a lot more work to make sure it was secure enough to use anywhere in production.

An idea, if you don't like your current solution of using a shell script from a system call: Write the file using regular Python code, with your regular user permissions. Then chown it (and move it, if necessary) with a sudo call.

like image 98
Blckknght Avatar answered Oct 15 '22 06:10

Blckknght