Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way for checking if the user of a script has root-like privileges?

I have a Python script that will be doing a lot of things that would require root-level privileges, such as moving files in /etc, installing with apt-get, and so on. I currently have:

if os.geteuid() != 0:     exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.") 

Is this the best way to do the check? Are there other best practices?

like image 776
Paul Hoffman Avatar asked May 10 '10 22:05

Paul Hoffman


People also ask

How do you check if a user is a root user?

The “root” user's UID is always 0 on the Linux systems. Instead of using the UID, you can also match the logged-in user name. The whoami command provides the currently logged user name.

How can I tell if a script is running as root?

Check root at start of script Some scripts need to be run as root and you may want to check at the start of that script that it is running as root. This can be done by checking the environment variable $EUID. This variable will hold the value 0 if it's being run as root.

How do I know if I have superuser?

Superuser privileges are given by being UID (userid) 0. grep for the user from the /etc/password file. The first numeric field after the user is the UID and the second is the GID (groupid). If the user is not UID 0, they do not have root privileges.

How do I get root in Python?

Python math function | sqrt() sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math.sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.


2 Answers

os.geteuid gets the effective user id, which is exactly what you want, so I can't think of any better way to perform such a check. The one bit that's uncertain is that "root-like' in the title: your code checks for exactly root, no "like" about it, and indeed I wouldn't know what "root-like but not root" would mean -- so, if you mean something different than "exactly root", perhaps you can clarify, thanks!

like image 76
Alex Martelli Avatar answered Sep 17 '22 09:09

Alex Martelli


Under the "Easier to Ask Forgiveness than Permission" principle:

try:     os.rename('/etc/foo', '/etc/bar') except IOError as e:     if (e[0] == errno.EPERM):        sys.exit("You need root permissions to do this, laterz!") 

If you are concerned about the non-portability of os.geteuid() you probably shouldn't be mucking with /etc anyway.

like image 28
msw Avatar answered Sep 17 '22 09:09

msw