Change to sudo user within a python script Change to sudo user within a python script python python

Change to sudo user within a python script


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 subprocessreturncode = subprocess.call(["/usr/bin/sudo", "/usr/bin/id"])


Don't try and make yourself sudo just check if you are and error if your not

class NotSudo(Exception):    passif os.getuid() != 0:    raise NotSudo("This program is not run as sudo or elevated this it will not work")


I've recently dealt with this problem while making a system installation script. To switch to superuser permissions, I used subprocess.call() with 'sudo':

#!/usr/bin/pythonimport subprocessimport shleximport getpassprint "This script was called by: " + getpass.getuser()print "Now do something as 'root'..."subprocess.call(shlex.split('sudo id -nu'))print "Now switch back to the calling user: " + getpass.getuser()

Note that you need to use shlex.split() to make your command usable for subprocess.call(). If you want to use the output from a command, you can use subprocess.check_output(). There is also a package called 'sh' (http://amoffat.github.com/sh/) that you can use for this purpose.