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\'
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/python
import subprocess
import shlex
import getpass
print "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.