Change to sudo user within a python script
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.