What is the best way for checking if the user of a script has root-like privileges?
Solution 1:
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!
Solution 2:
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.