Skip to main content
 首页 » 编程设计

python之在 python 中使用 azure sdk 从 VM 对象获取 IP

2025年02月15日33soundcode

我正在尝试从 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 地址对象的名称(并非所有对象都有公共(public) IP),我才能解析机器的 IP。

我需要能够使用这个 network_interface 并解析它上面的 IP

请您参考如下方法:

看来,为了获得 IP,您需要解析 vm.network_profile.network_interface 中给出的 URI。然后使用订阅和 nic 名称获取 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 来获取公共(public) IP