20

I am running a script as userA with root access, from this script I want to make a popen() call and run a different process as userB.

os.setuid() does not seem to work for this (unless I am doing this wrong?), and I would like to avoid a linux based solution such as su -userB -c <command>

Is there a pythonic way of running a process as userB while the script is running as userA?

EEP
  • 715
  • 1
  • 4
  • 17
  • 2
    The following answer has a really nice approach for this: http://stackoverflow.com/a/6037494/505154 – Andrew Clark Dec 11 '12 at 17:50
  • +1 for @F.J. Same approach I use in my own code. – jdi Dec 11 '12 at 18:10
  • 1
    +1 as well for @F.J that works great! If you want to summarize the answer here I'd be happy to give you a bit of rep and the answer credit as well. – EEP Dec 11 '12 at 18:34

1 Answers1

15

The following answer has a really nice approach for this: https://stackoverflow.com/a/6037494/505154

There is a working code example there, but the summary is to use subprocess.Popen() with a preexec_fn to set up the environment of the subprocess so that it executes as another user.

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 1
    In new versions of Python 3, it's as simple as adding the user argument to any subprocess method: https://stackoverflow.com/a/69560149/6296967 – Pavin Joseph Nov 07 '21 at 10:02