Becoming root within a Python script
Stephan Houben
stephan at pcrm.win.tue.nl
Fri Sep 24 03:19:38 EDT 1999
On 24 Sep 1999 00:29:02 -0400, François Pinard <pinard at iro.umontreal.ca> wrote:
>Mark Krischer <mkrisch at radiata.com> écrit:
>
>> why don't you call the python script using sudo, or make a wrapper
>> script that calls sudo <scriptname>.py
>
>I would prefer not run the script as root, but just become root, here and
>there, once in a while, in precise and unusual circumstances. And give
>the root password when those times come, and only then. I'm not found on
One thing you can do -- although I'm not sure if this is what you want --
is to have the script started with a setuid wrapper anyway, and then swap the
real and the effective user id, until the time comes when you want
to do something as "root", and then you swap them back.
This is not really Python-specific, and I guess you need to write a
Python wrapper for the system call setreuid(). But if you do
that (supposing you put that wrapper in a module uid), code
might look like this (obviously untested):
import os
import uid # implementing uid is left as an exercise for the reader
def swapreuid():
"""Swap real and effective user id.
"""
ruid = os.getuid() # get real user id
euid = os.geteuid() # get effective user id
uid.setreuid(euid, ruid)
Then make sure you get started with the effective uder id as "root",
and then do a swapreuid() the first thing in your script. This will
set the effective user id back to that of the user.
Then, when you have to do root magic, swap them back so you can
do the magic.
IIRC, this won't work with sudo, since sudo also sets the real uid to
"root" . So you really have to use a wrappper. By the way, I think
that it is even more secure to have the wrapper swap the real and
effective user id, instead of doing this in the first line of the
script. Whether this is *really* secure, I can't tell. Obviously,
it also depends on the contents of your script.
OK, I hope this is somewhat helpful.
If it's not, please delete this post. ;-)
Greetings,
Stephan
More information about the Python-list
mailing list