ESXi 5.1 list VMs via command line

Posted on Friday, April 24, 2015



 
I have an ESXi 5.1.0, I make use of it a lot.  Typically I am using VSphere 5.5 as my only view/control into the ESXi box.

I created this short script to lists my VMs.  It lists the vm_id, vm name, ip addresss and if its running or not in a JSON format.









I want to make this script just a command I can run all the time easily so I am placing it in /bin/lsvms

Open /bin/lsvms


  > vi /bin/lsvms


And place the following in it.


#!/bin/sh

vmarr=`vim-cmd vmsvc/getallvms | tail -n+2 | awk '{print $1":"$2}'`

echo "{ \"vms\": ["
first=true

for vm in $vmarr
do
  vnum=`echo $vm | cut -d ':' -f1`
  vname=`echo $vm | cut -d ':' -f2`
  vmdata=`vim-cmd vmsvc/get.guest $vnum`
  ip=`echo "$vmdata" | grep -m 1 'ipAddress' | cut -d '"' -f2`
  isrun=`echo "$vmdata" | grep -m 1 'guestState' | cut -d '"' -f2`

  if [ "$first" = true ];
  then
    first=false
  else
    echo ","
  fi

  echo -n "{\"id\":$vnum, \"name\":\"$vname\","

  #account for vms without ips (not running)
  if echo $ip | egrep -q ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$;
  #Next line would work in bash!
  #if [[ $ipaddr =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
  then
    echo -n "\"ip\":\"$ip\","
  fi


  if echo $isrun | egrep -q ^running$;
  then
    echo -n "\"isRunning\":true}"
  else
    echo -n "\"isRunning\":false}"
  fi

done

echo ""
echo "]}"


I was having a few problems with my script, with the regex portion.  I got some help from Martin Canaval on this post http://unix.stackexchange.com/questions/63248/pattern-matching-from-the-input-arguments [1]
Make it executable.


  > chmod 777 /bin/lsvms


Then run it.


  > lsvms





And out comes a readable list of my VMs in JSON format.



As a quick test I put the JSON in http://jsonlint.com/ [2]



And it's good.




References


[1]        Pattern matching from the input arguments
            Accessed 4/2015
[2]        JSON lint
            http://jsonlint.com/
            Accessed 4/2015


No comments:

Post a Comment