You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python查询Azure订阅中拥有Owner权限的用户?

找出Azure订阅中拥有Owner角色的所有用户(Python实现)

你可以通过结合azure.mgmt.authorization模块的角色定义查询和角色分配查询,同时指定expand参数获取用户主体信息,解决这个问题。以下是完整实现步骤:

1. 安装依赖包

确保安装所需的Python SDK包:

pip install azure-mgmt-authorization azure-identity

2. 完整代码示例

from azure.identity import DefaultAzureCredential
from azure.mgmt.authorization import AuthorizationManagementClient

# 替换为你的订阅ID
SUBSCRIPTION_ID = "your-subscription-id-here"

def get_owner_users():
    # 初始化认证客户端
    credential = DefaultAzureCredential()
    auth_client = AuthorizationManagementClient(credential, SUBSCRIPTION_ID)

    # 获取Owner角色的定义ID
    owner_role = next(
        role for role in auth_client.role_definitions.list(
            scope=f"/subscriptions/{SUBSCRIPTION_ID}",
            filter="roleName eq 'Owner'"
        )
    )
    owner_role_id = owner_role.id

    # 查询订阅下所有Owner角色的分配,同时展开主体信息
    owner_assignments = auth_client.role_assignments.list(
        scope=f"/subscriptions/{SUBSCRIPTION_ID}",
        filter=f"roleDefinitionId eq '{owner_role_id}'",
        expand="principal"
    )

    # 提取用户信息(过滤掉非用户类型的主体,比如服务主体、组)
    owner_users = []
    for assignment in owner_assignments:
        if assignment.principal_type == "User":
            owner_users.append({
                "用户ID": assignment.principal_id,
                "用户名": assignment.principal_name,
                "显示名称": assignment.principal_display_name,
                "角色分配ID": assignment.id
            })
    
    return owner_users

if __name__ == "__main__":
    owners = get_owner_users()
    print("拥有Owner角色的用户列表:")
    for idx, user in enumerate(owners, 1):
        print(f"\n用户{idx}:")
        for key, value in user.items():
            print(f"  {key}: {value}")

关键说明

  • 使用DefaultAzureCredential自动处理本地认证(支持Azure CLI、VS Code、服务 principal等多种方式)。
  • 通过role_definitions.list的filter参数精准定位Owner角色,获取其唯一ID。
  • 调用role_assignments.list时,通过filter筛选Owner角色的分配,同时指定expand="principal"拉取用户主体的详细信息(用户名、显示名称等)。
  • 代码中加入了principal_type == "User"的过滤,如果你需要包含组或服务主体,可以移除这个条件。

内容的提问来源于stack exchange,提问作者colbydh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:35:25