5

我希望我的应用程序中的某些功能只有在当前用户是管理员时才能访问。

如何确定当前用户是否在 Windows 上使用 Python 的本地管理员组中?

4

3 回答 3

6

你可以试试这个

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
于 2010-03-15T16:10:06.003 回答
2
import win32net


def if_user_in_group(group, member):
    members = win32net.NetLocalGroupGetMembers(None, group, 1)
    return member.lower() in list(map(lambda d: d['name'].lower(), members[0]))  


# Function usage
print(if_user_in_group('SOME_GROUP', 'SOME_USER'))

当然,在您的情况下,“SOME_GROUP”将是“管理员”

于 2016-04-29T19:48:19.150 回答
1

我想对Vlad Bezden 表示赞赏,因为如果没有他使用 win32net 模块,这里的答案将不存在。

如果您真的想知道用户是否有能力通过 UAC充当管理员,您可以执行以下操作。如果需要,它还会列出当前用户所在的组。
它适用于大多数(所有?)语言设置
本地组只需要以“Admin”开头,它通常会这样做......
(有人知道某些设置是否会有所不同吗?)

要使用此代码片段,您需要pywin32安装模块,如果您还没有,您可以从 PyPI 获取它:pip install pywin32

重要须知:
对于某些用户/编码人员来说,该功能os.getlogin()仅在 Windows 操作系统上的 python3.1 之后才可用可能很重要... python3.1 文档

win32net 参考

from time import sleep
import os
import win32net

if 'logonserver' in os.environ:
    server = os.environ['logonserver'][2:]
else:
    server = None

def if_user_is_admin(Server):
    groups = win32net.NetUserGetLocalGroups(Server, os.getlogin())
    isadmin = False
    for group in groups:
        if group.lower().startswith('admin'):
            isadmin = True
    return isadmin, groups


# Function usage
is_admin, groups = if_user_is_admin(server)

# Result handeling
if is_admin == True:
    print('You are a admin user!')
else:
    print('You are not an admin user.')
print('You are in the following groups:')
for group in groups:
    print(group)

sleep(10)

# (C) 2018 DelphiGeekGuy@Stack Overflow
# Don't hesitate to credit the author if you plan to use this snippet for production.

哦,在哪里from time import sleepsleep(10)

插入自己的进口/代码...

于 2018-05-07T08:50:12.253 回答