如何使用 Azure-SDK for Python 获取连接到 Azure 中特定虚拟机的 VNET(虚拟网络)信息

How to Get VNET (VirtualNetwork) Information connected to Specific Virtual Machine in Azure using Azure-SDK for Python

我想使用 Azure-SDK for Python 从 Azure 获取有关虚拟机的信息。 我可以通过在 computeClient

中提供资源组和虚拟机名称来获取 VM 的信息
compute_client = ComputeManagementClient(
    credentials,
    SUBSCRIPTION_ID
)

compute_client.virtual_machines.get(GROUP_NAME, VM_NAME, 展开='instanceView')

但是上面的代码没有给我 Vnet 信息

有人可以指导我吗

根据您的要求,您可以从 ComputeManagementClient SDK 获得的只是 VM 的网络接口,而不是 Vnet、子网等。这是网络接口的配置。

所以你需要做的就是获取网络接口的信息,然后它会告诉你网卡的配置,它包含网卡所在的子网。

我假设你只知道 VM 信息,那么你可以像这样获取 Vnet 信息:

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


subscription_Id = "xxxxxxxxx"
tenant_Id = "xxxxxxxxx"
client_Id = "xxxxxxxxx"
secret = "xxxxxxxxx"

credential = ServicePrincipalCredentials(
        client_id=client_Id,
        secret=secret,
        tenant=tenant_Id
        )

compute_client = ComputeManagementClient(credential, subscription_Id)
group_name = 'xxxxxxxxx'
vm_name = 'xxxxxxxxx'
vm = compute_client.virtual_machines.get(group_name, vm_name)
nic_name = vm.network_profile.network_interfaces[0].id.split('/')[-1]
nic_group = vm.network_profile.network_interfaces[0].id.split('/')[-5]

network_client = NetworkManagementClient(credential, subscription_Id)
nic = network_client.network_interfaces.get(nic_group, nic_name)
vnet_name = nic.ip_configurations[0].subnet.id.split('/')[-3]
vnet_group = nic.ip_configurations[0].subnet.id.split('/')[-7]

vnet = network_client.virtual_networks.get(vnet_group, vnet_name)

以上所有代码,我假设VM只有一个Nic,Nic只有一个配置。如果虚拟机有多个网卡,每个网卡有多个配置。您可以在 for each 循环中一个一个地获取它们。终于,你得到了你想要的有关Vnet的信息。