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?
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.
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.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With