I have a python script that is launched as root, I can't change it.
I would like to know if it's possible to exectute certain lines of this script (or all the script) as normal user (I don't need to be root to run this).
The reason is, I use notifications, and python-notify don't work in all machines in root (looks like this bug)
So ,do you know if it's possible to change it, with a subprocess, or other?
Thanks
I would like to know if it's possible to exectute certain lines of this script (or all the script) as normal user
Yes, it's possible—and a good idea.
Python's os
module has a group of functions to set the real, effective, and saved user and group id, starting with setegid
. What exactly each of these does is up to your platform, as far as Python is concerned; it's just calling the C functions of the same names.
But POSIX defines what those functions do. See setuid
and seteuid
for details, but the short version is:
- If you want to switch to a normal user and then switch back, use either
seteuid
or setreuid
, to set just effective, or real and effective, but not saved UID. Then use the same function again to set them back to root.
- If you want to run the whole script as a normal user and make sure you can't get root back, use
setresuid
instead, to set all three.
If you're using Python 3.1 and earlier, you don't have all of these functions. You can still use seteuid
to switch effective ID back and forth, but setuid
will… well, it depends on your platform, but I think most modern platforms will change saved as well as real, meaning you can't get root back. If you read the linked POSIX doc, there are a bunch of caveats and complexities in the POSIX documentation. If you only care about one platform, you probably want to read your local manpages instead, rather than reading about all of the cases and then trying to figure out which one covers your platform.
So ,do you know if it's possible to change it, with a subprocess, or other?
That isn't necessary (at least on a conforming POSIX system), but it can make things easier or safer. You can use subprocess
, multiprocessing
, os.fork
, or any other mechanism to launch a child process, which immediately uses setuid
to drop privileges—or even setresuid
to give up the ability to ever restore its privilege. When that child process is done with its task, it just exits.