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

如何用Python脚本通过API列出Azure VM镜像及相关实现疑问

使用Python脚本通过API列出Azure VM镜像

关于你的第二个问题:

当然可以用Python脚本通过Azure API列出VM镜像,下面是具体实现步骤和代码,帮你解决获取结果失败的问题。

前置准备

  • 安装依赖包:
    pip install azure-mgmt-compute azure-identity
    
  • 确保你的Azure账号拥有Microsoft.Compute/virtualMachineImages/read权限,本地调试可直接用Azure CLI执行az login完成登录。

实现代码

使用Azure官方Python SDK,通过ComputeManagementClient查询镜像信息,用DefaultAzureCredential做身份验证,支持本地CLI、托管身份等多种认证场景:

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient

# 替换为你的Azure订阅ID
SUBSCRIPTION_ID = "your-subscription-id"
# 替换为你需要的目标区域,比如"eastasia"
TARGET_LOCATION = "westus"

def fetch_vm_images():
    # 初始化客户端
    credential = DefaultAzureCredential()
    compute_client = ComputeManagementClient(credential, SUBSCRIPTION_ID)

    # 可添加其他公共镜像发布者,比如"RedHat"
    target_publishers = ["MicrosoftWindowsServer", "Canonical"]

    for publisher in target_publishers:
        print(f"\n=== 发布者: {publisher} ===")
        # 获取该发布者下的镜像产品
        offers = compute_client.virtual_machine_images.list_offers(TARGET_LOCATION, publisher)
        for offer in offers:
            print(f"  产品: {offer.name}")
            # 获取产品下的SKU
            skus = compute_client.virtual_machine_images.list_skus(TARGET_LOCATION, publisher, offer.name)
            for sku in skus:
                print(f"    SKU: {sku.name}")
                # 取最新5个版本避免输出过多,可移除切片获取全部版本
                versions = list(compute_client.virtual_machine_images.list(TARGET_LOCATION, publisher, offer.name, sku.name))[:5]
                for version in versions:
                    print(f"      版本: {version.name}")

if __name__ == "__main__":
    fetch_vm_images()

关键提示

  • 若要获取所有可用镜像发布者,可调用compute_client.virtual_machine_images.list_publishers(TARGET_LOCATION)
  • 不同区域的镜像库存存在差异,需确保TARGET_LOCATION参数正确
  • 生产环境建议添加异常处理,捕获认证失败、权限不足等错误

无结果排查

如果未获取到预期结果,检查以下几点:

  1. 确认订阅ID正确,且账号有权限访问该订阅资源
  2. 区域参数拼写是否正确,比如westus而非west-us
  3. 执行pip install --upgrade azure-mgmt-compute azure-identity更新依赖包
  4. 部分发布者/产品可能仅对特定订阅开放,可先尝试查询公共镜像(如MicrosoftWindowsServer、Canonical)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:01:27