Python – Is there a way to execute commands as a specific user in Python?

Is there a way to execute commands as a specific user in Python?… here is a solution to the problem.

Is there a way to execute commands as a specific user in Python?

As far as I know, there are about 3 ways to execute system commands in Python:

  1. os.system(command) -> exit_status

  2. os.popen(command [, mode='r' [, bufsize]]) -> pipe

  3. commands.getoutput(command)-> string

Now I need to control the executors of the system commands, except like this:

os.system('su xxx; ' + command)

Is there a more elegant way to achieve the same effect?

Solution

All the things you mentioned (by the way, the subprocess module has succeeded) is the way the process is generated. You sound like you’re looking for setuids. You can call a function that will do this, such as os.setuid, or, typically, depending on what your script does, you can run the entire script as an elevated user.

Related Problems and Solutions