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\'
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"])
If you are able to encapsulate just the necessary functionality requiring elevated privileges in a separate executable, you could use the setuid bit on the executable program, and call it from your user-level python script.
In this way, only the activity in the setuid-executable run as root, however executing this does NOT require sudo, i.e., root privileges. Only creating/modifying the setuid-executable requires sudo.
There are a few security implications, such as ensuring that your setuid executable program properly sanitizes any user input (e.g., parameters), so that it cannot be tricked into doing something it should not (confused deputy problem).
ref: http://en.wikipedia.org/wiki/Setuid#setuid_on_executables
edit: setuid only seems to work for compiled executables (binaries), and not interpreted scripts, so you may need to use a compiled setuid wrapper.
Use Tcl and Expect, plus subprocess to elevate yourself. So basically it's like this:
sudo.tcl
spawn sudo
expect {
"Password:" {
send "password"
}
}
sudo.py
import subprocess
subprocess.call(['tclsh', 'sudo.tcl'])
And then run sudo.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.
Are you talking about having the user input password half way through your execution? raw_input() can take a user input from console, but it will not mask the password.
>>>> y = raw_input()
somehting
>>> y
'somehting'
Don't try and make yourself sudo just check if you are and error if your not
class NotSudo(Exception):
pass
if os.getuid() != 0:
raise NotSudo("This program is not run as sudo or elevated this it will not work")