如何从Python脚本直接调用Azure CLI命令(替代subprocess)
直接用Python调用Azure操作的更好方案
当然有!比起用subprocess.check_output()调用Azure CLI命令行,微软官方提供的Azure SDK for Python(以及Microsoft Graph SDK)才是直接从Python代码中操作Azure资源的正统方式——比命令行调用更灵活、更易集成,还能避免解析命令行输出的麻烦。
下面我把你现有的三个CLI命令,对应转换成Python SDK的实现方式:
1. 创建Azure AD用户
现在微软推荐用Microsoft Graph SDK来操作Azure AD资源(Azure AD Graph已被弃用),先安装依赖:
pip install azure-identity msgraph-core
然后编写代码:
from azure.identity import ClientSecretCredential from msgraph_core import GraphClient # 初始化认证凭据(需要提前给你的Azure AD应用分配User.ReadWrite.All权限) tenant_id = "你的Azure租户ID" client_id = "你的Azure AD应用客户端ID" client_secret = "你的Azure AD应用客户端密钥" credential = ClientSecretCredential(tenant_id, client_id, client_secret) graph_client = GraphClient(credential=credential) # 构造用户数据 user_payload = { "accountEnabled": True, "displayName": "user", "mailNickname": "user", "userPrincipalName": "user@test.onmicrosoft.com", "passwordProfile": { "forceChangePasswordNextSignIn": False, "password": "Pass@word1" } } # 发送创建请求 response = graph_client.post("/users", json=user_payload) created_user = response.json() print(f"用户创建成功,ID: {created_user['id']}")
2. 分配Contributor角色
用azure-mgmt-authorization库来管理角色分配,安装依赖:
pip install azure-mgmt-authorization azure-identity
代码示例(可以复用上面创建的用户ID):
from azure.identity import AzureCliCredential from azure.mgmt.authorization import AuthorizationManagementClient import uuid # 用AzureCliCredential可以直接复用本地Azure CLI的登录状态,测试起来更方便 credential = AzureCliCredential() subscription_id = "你的Azure订阅ID" auth_client = AuthorizationManagementClient(credential, subscription_id) # Contributor角色的ID是固定的:b24988ac-6180-42a0-ab88-20f7382dd24c role_definition_id = f"/subscriptions/{subscription_id}/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c" # 生成唯一的角色分配名称(用UUID即可) role_assignment_name = str(uuid.uuid4()) # 创建角色分配 assignment = auth_client.role_assignments.create( scope=f"/subscriptions/{subscription_id}", role_assignment_name=role_assignment_name, parameters={ "role_definition_id": role_definition_id, "principal_id": created_user["id"] # 这里用前面创建用户返回的ID } ) print(f"角色分配成功,分配ID: {assignment.name}")
3. 创建服务主体(对应az ad sp create-for-rbac)
同样用Microsoft Graph SDK实现,代码如下(可以接着上面的GraphClient实例):
# 创建Azure AD应用(服务主体关联的应用) app_payload = { "displayName": "testapp", "passwordCredentials": [ { "endDateTime": "2025-12-31T23:59:59Z", "startDateTime": "2024-01-01T00:00:00Z", "secretText": "可选:自定义密码,不填的话Graph会自动生成" } ] } app_response = graph_client.post("/applications", json=app_payload) created_app = app_response.json() # 创建对应的服务主体 sp_response = graph_client.post("/servicePrincipals", json={"appId": created_app["appId"]}) created_sp = sp_response.json() print(f"服务主体创建成功,ID: {created_sp['id']},客户端ID: {created_app['appId']}")
为什么推荐用SDK而不是调用CLI?
- 结构化数据处理:直接返回JSON格式的资源对象,不用手动解析命令行输出的文本,减少出错概率
- 错误处理更精细:可以捕获Azure SDK抛出的特定异常,针对性处理问题
- 更好的集成性:能无缝融入你的Python业务逻辑,比如结合数据库、工作流等
- 更丰富的功能:SDK支持很多CLI没有覆盖的复杂操作场景
内容的提问来源于stack exchange,提问作者ClumsyPuffin
相关产品推荐
相关产品推荐

