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))
.
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 open
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With