When assigning IP addresses to a virtual machine, aka domain, you have two options -- either to assign a fixed IP to the machine or use DHCP for providing an IP address from a predefined range.
In environment in which you need to dynamically create groups of cooperating virtual machines the approach with fixed IP address is not feasible as it uses the network address range inefficiently and/or requires careful IP address management.
We needed the DHCP way. The problem is how to get the IP address for a virtual machine when all you have is only the machine's name.
There are two ways how to find out most of the information about a virtual machine, including its IP address:
- with a help from inside -- guest OS needs to have installed kind of hypervisor-specific software, so called guest agent, mediating communication of the host with the guest
- from outside -- gathering the desired information relies on standard tools of host OS and network connectivity
Virtualbox - Guest Additions
The IP address of the virtual machine can by retrieved from the machine properties with a single command vboxmanage guestproperty enumerate ${machine_name}. The information about guest network is available in guest properties only when the guest has installed Guest Additions, which limits the list of guest operating systems to Linux, Windows and Solaris.
To extract just the IP in bash or similar UNIX shell run:
vboxmanage guestproperty enumerate ${machine_name} | grep IP | cut -d " " -f 4 | cut -d "," -f 1
Libvirt - QEMU Guest Agent
Also QEMU has Guest Agent, supporting Linux and Windows guests, that can be use to get machine's IP address.
No Guest Tools, Just Linux
Second approach relies some basic knowledge about the virtual machine and the network interface it is connected to. Basically you need to know machine's MAC address and name of the NIC. For bridged networking the NIC is likely to be named br0.
Let's suppose the host OS is Linux. Similar approach should work on other operating systems but the tools will differ.
For the translation if MAC address to IP address I rely on arp-scan. It scans the whole network or given range if IP addresses and provides the MAC-to-IP mapping. To scan a whole network you can run arp-scan --interface ${bridge_name} -l , for larger networks you should provide IP address range to reduce time and memory footprint:
arp-scan --interface ${brige_name} ${low_ip_limit}-${high_ip_limit} .
So the complete bash script for getting virtual machine's IP address could look like this (for libvirt and br0 NIC):
#!/bin/bash
vm_name=$1
bridge_name="br0"
mac_address=`virsh dumpxml ${vm_name} | grep "mac address" | cut -d "'" -f 2`
arp_scan_record=`arp-scan --interface ${bridge_name} -l | grep $mac_address`
ip_address=`echo -n ${arp_scan_record} | cut -d " " -f 1`
echo -n "${ip_address}"
No comments:
Post a Comment