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

如何在Python脚本中执行az login --use-device-code并捕获设备码

在Python中捕获Azure设备码登录的URL和设备码

下面提供两种可行的实现方案,你可以根据环境需求选择:

方案1:使用subprocess调用Azure CLI

这种方法直接调用系统中的az命令,捕获输出后解析出登录URL和设备码,适合已安装Azure CLI的环境。

import subprocess
import re

def fetch_azure_device_credentials():
    # 执行az登录命令,捕获输出内容
    cmd_result = subprocess.run(
        ["az", "login", "--use-device-code"],
        capture_output=True,
        text=True
    )

    # 检查命令执行状态
    if cmd_result.returncode != 0:
        raise RuntimeError(f"Azure CLI命令执行失败: {cmd_result.stderr.strip()}")

    # 从输出文本中匹配登录URL和设备码
    output_text = cmd_result.stdout
    url_pattern = r"https://microsoft\.com/devicelogin"
    code_pattern = r"enter the code (\S+) to authenticate"

    url_match = re.search(url_pattern, output_text)
    code_match = re.search(code_pattern, output_text)

    if not url_match or not code_match:
        raise ValueError("无法从CLI输出中提取登录URL或设备码")

    return url_match.group(), code_match.group(1)

# 调用示例
if __name__ == "__main__":
    try:
        login_url, device_code = fetch_azure_device_credentials()
        print(f"引导用户访问: {login_url}")
        print(f"输入设备码完成登录: {device_code}")
        # 此处可将login_url和device_code传递给前端页面展示
    except Exception as err:
        print(f"出错了: {err}")

说明:

  • 需确保环境中已安装Azure CLI,且az命令在系统PATH中能被Python找到。
  • 用户完成登录后,当前Python进程会自动持有Azure会话凭证,后续可直接使用Azure SDK操作资源。

方案2:使用azure.cli.core库集成

这种方法直接调用Azure CLI的核心Python库,无需依赖外部az命令调用,适合需要深度集成的Python应用。

首先安装依赖包:

pip install azure-cli-core

实现代码:

from azure.cli.core import get_default_cli
import re

def get_device_login_details():
    cli_instance = get_default_cli()
    # 调用login命令并捕获输出
    cli_instance.invoke(["login", "--use-device-code"])
    output_content = cli_instance.result.output

    # 解析输出中的URL和设备码
    url_match = re.search(r"https://microsoft\.com/devicelogin", output_content)
    code_match = re.search(r"enter the code (\S+) to authenticate", output_content)

    if not url_match or not code_match:
        raise ValueError("无法提取登录所需的URL和设备码")

    return url_match.group(), code_match.group(1)

# 调用示例
if __name__ == "__main__":
    try:
        login_url, device_code = get_device_login_details()
        print(f"登录地址: {login_url}")
        print(f"设备码: {device_code}")
        # 将这两个值传递给前端页面即可
    except Exception as err:
        print(f"错误信息: {err}")

说明:

  • 该方法依赖azure-cli-core库,版本需与Azure CLI兼容,避免出现API不匹配问题。
  • 用户登录完成后,程序会自动获取会话凭证,可直接用于后续Azure操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:38:10