首页 > 解决方案 > 如何使用 python 列出 Azure 虚拟机?

问题描述

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

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

标签: pythonazurelistviewazure-vm-templates

解决方案


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

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

然后,要在 Python 中创建一个虚拟环境,以pip install azure通过pip install azure-mgmt-compute.

这是我的示例代码。

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 API and Is it Anyway to get ftpsState of azure web app (Azure Function app ) 使用 Python SDK?.

希望能帮助到你。


推荐阅读