Running one Python program from another as a different user

Jeff Schwab jeffrey.schwab at rcn.com
Fri Aug 12 18:33:59 EDT 2005


dwelch91 at gmail.com wrote:
> Greetings-
> This is on Linux... I have a daemon running as root and I want to
> execute another Python program as another user (a regular user). I have
> the name of the user and can use the 'pwd' and 'grp' modules to get
> that user's user and group ids. What I don't understand is how to then
> go about launching that new program. I had considered having the
> launched program switch itself back to the target user (somehow), but
> the launched program is graphical in nature (PyQt), and I am afraid of
> X11 locking out the display to user root (many distros seem to ship
> with server access for user root turned off). That might prevent the
> launched program from even starting?
> 
> Any ideas? My Google searching was not successful in figuring this
> out...

from subprocess import *

def run_as(username):
         pipe = Popen(["su", username], stdin=PIPE, stdout=PIPE)
         (out, err) = pipe.communicate("whoami")
         print out,


if __name__ == "__main__":
         import sys
         for user in sys.argv[1:]:
                 run_as(user)



More information about the Python-list mailing list