-
Notifications
You must be signed in to change notification settings - Fork 2
/
esx-halt.sh
executable file
·84 lines (61 loc) · 1.77 KB
/
esx-halt.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/bin/bash
# esx-halt.sh - Simple script to safely halt an ESXi host from ssh
# Copyright (C) 2011 Davide Ferrari
if [ $# -lt 1 ]
then
cat << EOF
Error! please specify a server name.
Usage:
$(basename $0) SERVERNAME
EOF
exit 255
fi
ESXI_HOST="$1"
ESXI_USER="root"
SSH_CMD="ssh -n ${ESXI_USER}@${ESXI_HOST}"
# SHUTDOWNER is used as a hack to prevent this script to shut down
# the guest where the script is running, and it must be set to a
# name known to ESXi. Leave it empty if you don't care about it.
SHUTDOWNER="ups-control"
function isVMPoweredOff() {
$SSH_CMD "vim-cmd vmsvc/power.getstate $1"|grep -q "Powered off"
}
function shutDownVM() {
echo -n "Shutting down VMID $1... "
$SSH_CMD "vim-cmd vmsvc/power.shutdown $1" >/dev/null 2>&1 && { echo OK; return 0; } || { echo KO; return 255; }
}
function powerOffVM() {
echo -n "Powering off (forcing) VMID $1... "
$SSH_CMD "vim-cmd vmsvc/power.off $1" >/dev/null 2>&1 && { echo OK; return 0; } || { echo KO; return 255; }
}
function stopAllVMs() {
$SSH_CMD "vim-cmd vmsvc/getallvms"|tail -n +2 |grep -v "${SHUTDOWNER}"|awk '{print $1}'|while read vmid
do
if ! isVMPoweredOff $vmid
then
shutDownVM $vmid || powerOffVM $vmid
fi
done
}
function haltHost() {
echo -e "\nNow halting the host..."
$SSH_CMD "halt"
}
function checkAllVMsOff() {
echo -n "Checking if all VMs are really powered off..."
$SSH_CMD "vim-cmd vmsvc/getallvms"|tail -n +2 |grep -v "${SHUTDOWNER}"|awk '{print $1}'|while read vmid
do
c=0
echo -n " $vmid"
while ! isVMPoweredOff $vmid
do
sleep 5
((c++))
(( c > 12 )) && { echo "Giving up on $vmid"; break; }
echo -n "."
done
echo -n " OFF"
done
}
# do the real stuff
stopAllVMs && checkAllVMsOff && haltHost