Python - 检查用户是否具有管理员权限 [英] Python - checking if a user has administrator privileges

查看:73
本文介绍了Python - 检查用户是否具有管理员权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 3.x 编写一个小程序作为自学项目.我的想法是让程序允许用户输入两个文本字段,然后将用户的输入插入到两个特定注册表项的值中.

I'm writing a little program as a self-learning project in Python 3.x. My idea is for the program to allow two fields of text entry to the user, and then plug the user's input into the value of two specific registry keys.

是否有一种简单的方法可以检查当前用户是否可以访问注册表?我宁愿它清楚地告诉用户他/她需要管理员权限,而不是因为程序试图访问受限区域而发疯和崩溃.

Is there a simple way to make it check if the current user can access the registry? I'd rather it cleanly tell the user that he/she needs administrator privileges than for the program to go nuts and crash because it's trying to access a restricted area.

我希望它在程序启动后立即进行此检查,然后再向用户提供任何输入选项.这需要什么代码?

I'd like it to make this check as soon as the program launches, before the user is given any input options. What code is needed for this?

如果不明显,这是针对 Windows 平台的.

in case it isn't obvious, this is for the Windows platforms.

推荐答案

我需要一个简单的 Windows/Posix 解决方案来测试用户是否具有文件系统的 root/admin 权限,而无需安装第三方解决方案.我知道依赖环境变量时存在漏洞,但它们适合我的目的.或许可以扩展这种方法来读/写注册表.

I needed a simple, Windows/Posix solution to test if a user has root/admin privileges to the file system without installing an 3rd party solution. I understand there are vulnerabilities when relying on environment variables, but they suited my purpose. It might be possible to extend this approach to read/write the registry.

我在 WinXP、WinVista 和 Wine 上使用 Python 2.6/2.7 对此进行了测试.如果有人知道这在 Pyton 3.x 和/或 Win7 上不起作用,请提供建议.谢谢.

I tested this with Python 2.6/2.7 on WinXP, WinVista and Wine. If anyone knows this will not work on Pyton 3.x and/or Win7, please advise. Thanks.

def has_admin():
    import os
    if os.name == 'nt':
        try:
            # only windows users with admin privileges can read the C:\windows\temp
            temp = os.listdir(os.sep.join([os.environ.get('SystemRoot','C:\\windows'),'temp']))
        except:
            return (os.environ['USERNAME'],False)
        else:
            return (os.environ['USERNAME'],True)
    else:
        if 'SUDO_USER' in os.environ and os.geteuid() == 0:
            return (os.environ['SUDO_USER'],True)
        else:
            return (os.environ['USERNAME'],False)

这篇关于Python - 检查用户是否具有管理员权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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