Mass VM Shutdown Script

0 Comments ESX 3.5 Tips, ESXi 3.5 Tips

Well, if you haven’t already figured out I’m big on shell scripts and Unix/Linux in general, so when my company informed me that they needed to bring down one of our NetApp FAS clusters for system maintenance, the wheels in my head started turning.  I’m sorry this isn’t in our beloved Powershell scripting language, but I’m old school and needed to write a shell based script to gracefully shutdown all my virtual machines.

I know there are other ways to do this, but I really don’t want to wake up at 3AM on Sunday to do it.  So below is my shell script, which I’ve scheduled in cron on one of my ESX 3.5 hosts.

#!/bin/sh -x
# set path and date
DATE=`date +%m.%d.%G.%H%M`
PATH=$PATH:/bin:/usr/bin:/usr/sbin

date
echo “Attempting graceful shutdown of Virtual Machines on host dpcrc-vmdevsap1…”

# start for loop to grab VMIDs then send power.shutdown requests using vim 3 seconds apart
for i in `vmware-vim-cmd vmsvc/getallvms | sed ‘1d’ | awk ‘{print $1}’`
do
vmware-vim-cmd vmsvc/power.shutdown $i
sleep 3
done
echo “Successfully sent shutdown sequence to Virtual Machines on host dpcrc-vmdevsap1”

date
echo “Attempting graceful shutdown of Virtual Machines on host dpcrc-vmdevsap2…”

# in this for loop I’m connecting via ssh to my other esx host(s), you can multiply this for
# as many hosts as you have.  I have 8 I need to do but I’m leaving them out for simplicity
# in the blog.  Please remember to have your other ESX hosts ssh keys in the authorized key file
# of the host your starting the script from

for i in `ssh dpcrc-vmdevsap2 vmware-vim-cmd vmsvc/getallvms | sed ‘1d’ | awk ‘{print $1}’`
do
ssh dpcrc-vmdevsap2 vmware-vim-cmd vmsvc/power.shutdown $i
sleep 3
done
echo “Successfully sent shutdown sequence to Virtual Machines on host dpcrc-vmdevsap2”

Here is the cron so you can see exactly when I’m running this;

50 3 18 1 0 /usr/sbin/massvmshutdown > /var/log/massvmshutdown 2>&1

As you can see, I’m running this at 03:50 on 1/18 and the 0 day of the week (Sunday).  I did this so just in case if I forget to remove it from the cron, it will not run again until 1/18 falls on a Sunday (2015). Also I am outputting std out to a log file so I can review it after.

One big thing that this script would require is the ability to SSH from one ESX host to another, without be prompted for a password.  I covered how to do this in another blog post, which can be found here.