how to spawn a process under different user
nick at craig-wood.com
Fri Jul 3 10:30:02 CEST 2009
Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
> En Thu, 02 Jul 2009 19:27:05 -0300, Tim Harig <usernet at ilthio.net>
> > On 2009-07-02, sanket <sanket.s.patel at gmail.com> wrote:
> >>> sanket wrote:
> >>> > I am trying to use python's subprocess module to launch a process.
> >>> > but in order to do that I have to change the user.
> >> I am using python 2.4 on centos.
> > I have never done this in python; but, using the normal system calls in C
> > the process is basically:
> > 1. fork() a new process
> > 2. the child process changes its user id with setreuid() and
> > possibly its group id with setregid()
> > 3. then the child exec()s new process which replaces itself
> > All of the necessary functions should be under the os module on POSIX
> > operating systems.
> How to do that using the subprocess module: write a function for item (2)
> above and pass it as the preexec_fn argument to Popen. preexec_fn is
> executed after fork() and before exec()
If you are forking 100s of processes a second you want to use the
method above, however I think it is easier to use su (assuming you
start off as root),
so instead of passing
['mycommand', 'my_arg1', 'my_arg2']
to Popen, pass
['su', '-', 'username', '-c', 'mycommand my_arg1 my_arg2']
There is some opportunity for quoting problems there, but it is easy!
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list