检查脚本用户是否具有类似 root 的权限的最佳方法是什么? [英] What is the best way for checking if the user of a script has root-like privileges?

查看:41
本文介绍了检查脚本用户是否具有类似 root 的权限的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 脚本,它可以做很多需要 root 权限的事情,例如在/etc 中移动文件、使用 apt-get 安装等等.我目前有:

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 "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!")

如果您担心 os.geteuid() 的不可移植性,您可能无论如何都不应该使用 /etc.

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

这篇关于检查脚本用户是否具有类似 root 的权限的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆