list-all-vms.sh

Lister alle vm-er på en eller flere ESX-servere

#! /bin/bash
#
# Return all virtual machines on ESXi-servers, $esx_servers
# Run as root, and make shure that root can log in on $esx_servers
# without password.
#  https://kb.vmware.com/s/article/1002866
#  http://www.linuxproblem.org/art_9.html
#
# hans@sandsdalen.net

esx_servers="esx1 esx2"
# test
#esx_servers="esx1"

name_start_pos=7

function list-vms
# will list vms commaseparated
# format: paa linje
# <vmid> <name> <File> <Guest OS> <Version> <Annotation>
# - File has format "[xxx] filnavn"
# - name starts in position $name_start_pos + 1
#
# Annotation is not shown
{
   esxi_server=$1 
   lines=$(ssh $esxi_server vim-cmd vmsvc/getallvms)

   echo "$lines" | while read -r line
   do

      # Line must start with a number
      if [[ $line =~ ^[0-9] ]]; then
         # printf "$line\n"

         # remove everything after [
         l1=${line%%[*}

         # vmid is first word
         vmid=${l1%% *}

         # name is the rest of $l1
         name=${l1:$name_start_pos}
         # remove blanks
         name=${name%% *}

         # set $file to $line except from $l1 (see above)
         file=${line#$l1}
         file=${file/.vmx */.vmx}

         # Guest OS
         guest_os1=${line/*.vmx/}
         # remove blanks
         guest_os=$(echo $guest_os1 | cut -f1 -d" ")

         # Version
         version=$(echo $guest_os1 | cut -f2 -d" ")

         echo "$esxi_server","$vmid,\"$name\",\"$file\",\"$guest_os\",\"$version\""

      fi
   done
}

for server in $esx_servers
do
   list-vms $server
done

Se også