Change to sudo user within a python script

Kraken18 picture Kraken18 · Mar 4, 2011 · Viewed 48.1k times · Source

I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running 'sudo python filename.py' isn't an option, which leads me to my question. Is there a way of changing to sudo half way through a python script, security isn't an issue as the user will know the sudo password the program should run in the following way to illustrate the issue

  1. program running as normal user
  2. ...... performing operations
  3. user enters sudo password
  4. user changed to sudo
  5. sub program requiring sudo permission is run
  6. on trigger even (end of sub program) user becomes normal user again
  7. ...... performing operations

My problem lies in step 3, any pointers or frameworks you could suggest would be of great help.

Cheers

Chris

Answer

nealmcb picture nealmcb · Mar 2, 2012

It is better to run as little of the program as possible with elevated privileges. You can run the small part that needs more privilege via the subprocess.call() function, e.g.

import subprocess
returncode = subprocess.call(["/usr/bin/sudo", "/usr/bin/id"])