有没有pythonapi可以获取Azu中虚拟机的IP地址(内部或外部)

2024-05-05 18:49:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用pythonsdk控制Azure中的vm。有没有API可以根据虚拟机的名称获取虚拟机的IP地址(内部或外部)?在


Tags: 名称apivmazurepythonsdk
2条回答

根据我的理解,我认为您应该使用azuresdkforpython获取azurevm的公共和私有ip地址。在

要获取这些ip地址(内部和外部),请参阅下面的代码。在

from azure.mgmt.network import NetworkManagementClient, NetworkManagementClientConfiguration

subscription_id = '33333333-3333-3333-3333-333333333333'

credentials = ...

network_client = NetworkManagementClient(
    NetworkManagementClientConfiguration(
        credentials,
        subscription_id
    )
)

GROUP_NAME = 'XXX'
VM_NAME = 'xxx'
PUBLIC_IP_NAME = VM_NAME

public_ip_address = network_client.public_ip_addresses.get(GROUP_NAME, PUBLIC_IP_NAME)
print(public_ip_address.ip_address)
print(public_ip_address.ip_configuration.private_ip_address)

作为参考,您可以参考下面的文档来了解上面代码的详细信息。在

  1. Resource Management Authentication使用Python作为变量{}。在
  2. Create the management client表示变量{}。在
  3. 有关azure.mgmt.network包的详细信息,请参阅http://azure-sdk-for-python.readthedocs.io/en/latest/ref/azure.mgmt.network.html。在

对于那些没有为他们的虚拟机分配公共IP的人,有一种方法可以在不创建公共IP的情况下获得私有IP。在

from azure.mgmt.network import NetworkManagementClient, NetworkManagementClientConfiguration

subscription_id = '' 
credentials = UserPassCredentials(
    'user@yes.com',
    'password',
)

network_client = NetworkManagementClient(
    credentials,
    subscription_id
)

private_ip = network_client.network_interfaces.get(GROUP_NAME, NETWORK_INTERFACE_NAME).ip_configurations[0].private_ip_address

这是可行的,并在azuresdkforpythonversion2.0.0rc6上进行了测试。在

相关问题 更多 >