I want to control the VMs in Azure with python SDK. Is there any API that can get a VM's IP address (internal or external) according to VM's name?
Asked
Active
Viewed 3,682 times
3
-
I believe this question may be answered at [this stack overflow question](http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib) – Mark Roper May 17 '16 at 01:57
-
I mean getting IP address of VMs with Azure python SDK. This is because I want to remote control the VMs in Azure with it's SDK. It's a different question. – skyline_z May 17 '16 at 02:30
-
You probably need to clarify the question a bit. Is this from within the VM, or from a control machine somewhere? – Shayne May 17 '16 at 02:49
2 Answers
7
Based on my understanding, I think you want to get the public & private ip addresses of a Azure VM using Azure SDK for Python.
For getting these ip addresses (internal & external), please see the code below.
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)
As reference, you can refer to the documents below to know the details of the code above.
- Resource Management Authentication using Python for the variable
credentials
. - Create the management client for the variable
network_client
. - More details for the
azure.mgmt.network
package, please see http://azure-sdk-for-python.readthedocs.io/en/latest/ref/azure.mgmt.network.html.

Peter Pan
- 23,476
- 4
- 25
- 43
-
2Very convoluted (thank you Microsoft) way of getting IP addresses, but works and saved my day. Small correction, currently the network_client is created like this: network_client = NetworkManagementClient( credentials, subscription_id ) – alexvicegrab Nov 25 '16 at 22:40
-
Hold on. This only works if the public IP address object has the same name as the VM... or am I missing something? – Pedro Perez Jul 11 '19 at 11:51
1
For the people that don't have public IP assigned to their VM there is a way to get the private IP without creating the public 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
This works and is tested on azure-sdk-for-python version 2.0.0rc6.

Strahinja Radman
- 116
- 1
- 5