python - 如何使用 python 列出 Azure 虚拟机?
问题描述
我正在尝试使用 python 代码列出 Azure VM。有人可以帮我解决这个问题吗?
我已经尝试过浏览 Microsoft 网站上的代码,但我不清楚。
解决方案
首先,您需要按照Register your client application with Azure AD
Azure 官方文档的部分Azure REST API Reference
在 Azure 门户上向 Azure AD 注册应用程序,以获取所需的参数client_id
并secret
进行身份验证以列出 VM。
并且,您继续获取其他必需的参数subscription_id
和tenant_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?.
希望能帮助到你。
推荐阅读
- c++ - 在运行时在代码中调整大小时如何避免dockwidget与主窗口中的其他对象重叠?
- javascript - 如何虚拟更改谷歌分析中的综合浏览量?
- javascript - element.getAttribute 不是函数
- mysql - MAMP & MyPHPAdmin 格式参数不正确
- sql - 使用 read.csv.sql,R 创建 SQL 文件时如何过滤双引号
- database - 如何在 select 语句中获取引用?
- sql - 找不到数据类型 - 错误仅在较大的脚本内发生
- routes - zf3 翻译路线 - 找不到翻译器
- javascript - 在没有 NodeJs 的客户端站点上使用带有 javascript 的 Swagger
- javascript - 将当前样式表保存到本地存储