确定当前用户是否在管理员组中(Windows/Python)

5

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

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

3个回答

6
你可以尝试使用这个链接
import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()

1
当UAC被激活时,IT无法工作,似乎这个函数检查了进程权限。 - user1198490
IsUserAnAdmin() 只能在 Windows XP 上使用,无法在后续版本的 Windows 上正常工作。 - Nathan Osman

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”将是“管理员”。

1
我希望给Vlad Bezden一些赞誉,因为如果没有他使用win32net模块的话,这个答案就不会存在。
如果您真的想知道用户是否有超越UAC的管理员权限,可以执行以下操作。如果需要,它还会列出当前用户所在的组。
它将适用于大多数(所有?)语言设置
本地组只需以“Admin”开头,通常情况下都是如此...
(有人知道有些设置会有所不同吗?)
要使用此代码片段,您需要安装pywin32模块, 如果您还没有它,可以从PyPI获取:pip install pywin32 重要提示:
对于Windows操作系统,自python3.1以来才有函数os.getlogin(),这可能对某些用户/编码者很重要... python3.1 Documentation

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) 的位置:

插入自己的导入/代码...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接