Friday, September 12, 2014

List VMs with VNC port information

Objective: Create a shell script to list all VM (both running and inactive) with VNC port information in the similar output format of the standard virsh tool.
 Id    Name                           State         Vnc
------------------------------------------------------------
 2     vm1                            running       :0
 3     vm2                            running       :1
 -     vm3                            shut off

Method 1: The dirty method (This method yields the same visual output as preferred but it takes longer time to load due to excessive "virsh" commands)

#!/bin/bash
echo " Id    Name                           State         Vnc"
echo "------------------------------------------------------------"
for guestname in $(virsh list --name); do
        printf " %-6s%-31s%-14s%-6s\n" "$(virsh domid $guestname)" "$guestname" "$(virsh domstate $guestname)" "$(virsh vncdisplay $guestname)"
done
virsh -q list --inactive

Method 2: The array method (This method minimize the number of virsh calls to enhance performance.
echo " Id    Name                           State         Vnc"
echo "------------------------------------------------------------"
declare -a fields
indx=0
# array initialization is required to format an array of strings
# the "for...do...done" loop best fit the array formation of each "cell" in the virsh list table forms a single element in the array
for guestline in $(virsh -q list); do
        fields[((indx++))]=$guestline
done
max=${#fields[@]}

for ((count=0; count<$max; count=$count+3)); do
        printf " %-6d%-31s%-14s%-6s\n" ${fields[$count]} "${fields[$((count + 1))]}" "${fields[$((count + 2))]}" "`virsh vncdisplay ${fields[$((count))]}`"
done
virsh -q list --inactive

No comments:

Post a Comment