【问题标题】:Get IP from VM object using azure sdk in python在 python 中使用 azure sdk 从 VM 对象获取 IP
【发布时间】:2017-04-05 08:40:50
【问题描述】:

我正在尝试从 Azure 订阅中获取所有 IP(附加到 VM)。

我已经使用

拉出了所有虚拟机
compute_client = ComputeManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials,subscription_id)


 for vm in compute_client.virtual_machines.list_all():
      print(vm.network_profile.network_interface)

但是 network_profile 对象似乎只是一个指针,我已经阅读了文档,无法弄清楚如何将每个 vm 链接到其附加的 IP 地址

我遇到了这个:Is there any python API which can get the IP address (internal or external) of Virtual machine in Azure

但似乎有些事情发生了变化。

只有知道 Public_IP 地址对象的名称(并非所有对象都有公共 IP),我才能解析机器的 IP。

我需要能够获取此网络接口并解析其上的 IP

【问题讨论】:

    标签: python azure cloud


    【解决方案1】:

    所以看来,为了获取 IP,您需要解析vm.network_profile.network_interface 中给出的 URI。然后使用订阅和网卡名称获取 IP using network_client.network_interfaces.get()

    我使用的代码如下:

    compute_client = ComputeManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials,subscription_id)
            try:
                get_private(compute_client, network_client)
            except:
                print("Auth failed on "+ subscription_id)
    
    
    
    def get_private(compute_client, network_client):
    
    
        for vm in compute_client.virtual_machines.list_all():
            for interface in vm.network_profile.network_interfaces:
                name=" ".join(interface.id.split('/')[-1:])
                sub="".join(interface.id.split('/')[4])
    
                try:
                    thing=network_client.network_interfaces.get(sub, name).ip_configurations
    
                    for x in thing:
                        print(x.private_ip_address)
    
                except:
                    print("nope")
    

    在此示例中,您还可以通过 x.public_ip_address 获取公共 IP

    【讨论】:

      【解决方案2】:

      正如你所说,确实有一些变化,但变化不大。

      首先如下,NetworkManagementClientConfiguration已被删除,详情见link

      network_client = NetworkManagementClient(credentials,subscription_id)
      

      其次,根据source code,参数public_ip_address_name是子网名称,不再是vm名称。

      # Resource Group
      GROUP_NAME = 'azure-sample-group-virtual-machines'
      # Network
      SUBNET_NAME = 'azure-sample-subnet'
      PUBLIC_IP_NAME = SUBNET_NAME
      public_ip_address = network_client.public_ip_addresses.get(GROUP_NAME, PUBLIC_IP_NAME)
      

      然后,您还可以通过IPConfiguration 来自PublicIPAddressprivate_ip_addresspublic_ip_address

      print(public_ip_address.ip_configuration.private_ip_address)
      print(public_ip_address.ip_configuration.public_ip_address)
      

      【讨论】:

      • 嗨,要完成彼得潘解决方案,从 VM 获取 IP 的唯一方法是获取 VM 属性中的 ID,然后解析 ID 以获取内部的不同部分(资源组、子网等),然后调用网络客户端。这可能会有所帮助:github.com/Azure/azure-sdk-for-python/issues/534
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多