判断当前用户是否在管理员组中(Windows/Python)
我想让我应用程序中的某些功能只有在当前用户是管理员时才能使用。
我该如何用Python在Windows上判断当前用户是否在本地管理员组里呢?
3 个回答
1
我想给 Vlad Bezden 一些赞誉,因为如果没有他使用的 win32net 模块,这个答案就不会存在。
如果你真的想知道用户是否有权限在通过 UAC 后 作为管理员操作,你可以这样做。这个方法还会列出当前用户所在的组,如果需要的话。
它适用于大多数(几乎所有?)语言设置。
本地组的名称只需要以“Admin”开头,通常都是这样的...
(有没有人知道某些设置会有所不同吗?)
要使用这个代码片段,你需要安装 pywin32
模块,如果你还没有安装,可以从 PyPI 获取:pip install pywin32
重要提示:
对某些用户/程序员来说,函数 os.getlogin()
仅在 Windows 操作系统的 Python 3.1 及以上版本中可用...
python3.1 文档
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 sleep
和 sleep(10)
的地方:
插入你自己的导入/代码...
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' 就是 'administrators'(管理员)。
6
你可以试试这个链接:
import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()