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?
Under the EAFP (Easier to Ask Forgiveness than Permission) principle:
import errno
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.