I would like to make my user run as sudo and as a normal user depending on his choice.He could use sudo or normal but on not using sudo I have to disable some functionalities to get rid of errors.So how could I know that user as given me sudo permissions to execute or not? I am building my application on python.
-
2If I understand correctly, you're looking for this http://stackoverflow.com/questions/2806897/what-is-the-best-practices-for-checking-if-the-user-of-a-python-script-has-root ? – Aran-Fey Jul 25 '16 at 18:31
-
2The best, safest and most robust way is to just try the operation, and let the user know if it fails and the likely reason why (and maybe offer to invoke sudo/gksudo on their behalf). The crappiest way is to check for a UID of 0. – that other guy Jul 25 '16 at 18:32
-
@thatotherguy: Maybe so, but I think it's reasonable for a script to take a `--no-root` option (or similar) that avoids doing anything rooty. – ruakh Jul 25 '16 at 18:40
1 Answers
After having read your question a few times, I think I know what you are asking. Am I correct in thinking that you want to know how to tell whether or not your python script as root permissions during runtime?
If you really want to check ahead of time, you could query the system for the user id with os.geteuid()
and if it returns 0
, your script is running as root.
However, an alternative approach would be to simply run the code that needs root privileges in a try
block. Depending on exactly what you are trying to do, this may or may not be a better solution. You would also have to know the type of exception to expect if you don't have the needed privileges. This makes it a little harder to write but the code may end up more flexible to changing circumstances, such as users with enough privileges but not root. It may also make for more portable code, although the exception may change from one OS to another.
E.g.
try:
function_that_needs_root()
except MyNotRootException:
print "Skipping function_that_needs_root: you are not root"

- 416
- 2
- 5