simple linux Script to shut down VMs and ESXi host
Here is a very simple linux bash script to shut down all VMs of a ESXi host and the host itself, for example when a power failure occurs, this script can be used in UPS software. Some time ago a posted how to use such script in an HPE UPS environment. You can find the post here.
The script is run-able in a vMA (vSphere Management Assistant). But vSphere 6.5 is the last release, vMA is available. All future releases will not include a vMA. More information here. When I need to update the script to a newer version (authentication will change), I will post an update.
# Parameter: # $1: Host to shutdown # $2: Seconds between VM shutdown # $3: Seconds before the Host is shut down # $4: Seconds to wait to the start of the script # Time to wait, to avoid to shutdown all hosts at once sleep $4s # create a log-file NOW=$(date +"%Y-%m-%d_%H%M%S") LOGFILE="/tmp/UPS-shutdown-$NOW.log" > $LOGFILE # add local host to shutdown to management /opt/vmware/vma/bin/vifp addserver $1 --username root --password 'PASSWORD' 2>>$LOGFILE # set as default-server source /opt/vmware/vma/bin/vifptarget --set $1 2>>$LOGFILE # set name of vMA itself VMA=`hostname -s` # loop to shutdown VMs, except vMA itself for i in `vmware-cmd -l`; do if [ `vmware-cmd $i getstate | egrep -c "on"` -eq 1 ]; then echo $i >> $LOGFILE if [ `echo $i | egrep -i -c $VMA` -ge 1 ]; then echo "Skip shut down of vMA" >> $LOGFILE else echo "Shut down $i" >>$LOGFILE vmware-cmd "$i" stop soft 2>>$LOGFILE sleep $2s fi fi done # wait for $3 seconds sleep $3s # shut down hosts - with NO Maintenance-Mode! echo "Shut down Host!" >> $LOGFILE vicfg-hostops --operation shutdown --force 2>>$LOGFILE
- 8: Script waits for
- 11: Set variable
NOWto current date and time.
- 12: Defines logfile path and file-name.
- 13: Creates logfile for this run.
- 16-19: Adds host to shut down (
$1) to vMA target list and sets as default.
2>>redirects errors to logfile.
- 22: Set variable
VMAto hostname of vMA. This is because we want to skip vMA-VM to shut down. This happens in row 28. Therefore it is necessary to have the same hostname and inventoryname.
- 25-36: Loop to shut down VMs running on host.
- 26: Select running VMs.
- 27: Write VM-name to logfile.
- 28-29: Skip vMA and log.
- 31: Log VM to shut down.
- 32: Execute shut down VM.
- Wait for
- 39: Wait for
- 42: Final log-entry.
- 43: Shutting down ESXi host and log errors to logfile.