【问题标题】:How to list Azure vms using python?如何使用 python 列出 Azure 虚拟机?
【发布时间】:2026-02-15 17:15:01
【问题描述】:

我正在尝试使用 python 代码列出 Azure VM。有人可以帮我解决这个问题吗?

我已经尝试过浏览微软网站上的代码,但我不清楚。

【问题讨论】:

  • 哈立德您好,欢迎来到 Stack Overflow!对于这个网站来说,这不是一个很好的问题,我们是关于修复损坏的代码,而不是帮助您阅读文档。这是一个方便的帖子,可以帮助您将来在这里提出更好的问题:*.com/help/how-to-ask
  • 您好 Hoog,感谢您的欢迎和反馈。我来这里是为了学习,我会在如何提问方面做得更好。再次感谢您的评论:)

标签: python azure listview azure-vm-templates


【解决方案1】:

首先,您需要按照 Azure 官方文档 Azure REST API ReferenceRegister your client application with Azure AD 部分在 Azure 门户上向 Azure AD 注册应用程序,以获得所需的参数 client_idsecret 进行身份验证以列出 VM。

并且,您继续获取其他必需参数subscription_idtenant_id

然后,在 Python 中创建一个虚拟环境,通过 pip install azure 安装 Azure SDK for Python,或者通过 pip install azure-mgmt-compute 安装 Azure Compute Management for Python。

这是我的示例代码。

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

credentials = ServicePrincipalCredentials(
    client_id='<your client id>',
    secret='<your client secret>',
    tenant='<your tenant id>'
)

subscription_id = '<your subscription id>'
client = ComputeManagementClient(credentials, subscription_id)

如果只是按资源组列出虚拟机,使用函数list(resource_group_name, custom_headers=None, raw=False, **operation_config)如下代码。

resource_group_name = '<your resource group name>'
vms_by_resource_group = client.virtual_machines.list(resource_group_name)

或者你想列出你订阅中的所有虚拟机,使用函数list_all(custom_headers=None, raw=False, **operation_config)作为下面的代码。

all_vms = client.virtual_machines.list_all()

作为参考,我认为有两个 SO 线程可能有助于更深入地理解:How to get list of Azure VMs (non-classic/Resource Managed) using Java APIIs it anyway to get ftpsState of azure web app (Azure Function app) using Python SDK?

希望对你有帮助。

【讨论】:

  • 非常感谢。这很有帮助。