nike nike - 1 year ago 55
Linux Question

differentiate sudo <command> and <command>

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.

Answer Source

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.


except MyNotRootException:
    print "Skipping function_that_needs_root: you are not root"