因爲近期大廈須要維護,所以通知晚上須要斷電,所以寫了一個針對ESXI主機自動關機的腳本,時間倉促,腳本還有許多能夠改進的地方,勿噴。vim
具體腳本以下:bash
#/bin/bash
off=`esxcli vm process list|grep World |cut -c 13- |wc -l`
status=`vim-cmd /hostsvc/hostsummary | grep inMaintenanceMode|cut -c 27`
if [ $off == 0 ] ;then
[ $status == "f" ] && vim-cmd hostsvc/maintenance_mode_enter 1&> /dev/null && halt || halt
else
esxcli vm process list|grep World |cut -c 13- >tmp.txt
on=`esxcli vm process list|grep World |cut -c 13- |wc -l`
for i in `seq 1 $on`
do
hostid=`sed -n " $i p " ./tmp.txt`
esxcli vm process kill -t soft -w $hostid 1&> /dev/null
sleep 3
done
rm -rf ./tmp.txt
off=`esxcli vm process list|grep World |cut -c 13- |wc -l`
if [ $off == 0 ] ;then
vim-cmd hostsvc/maintenance_mode_enter 1&> /dev/null
halt
else
ps |grep vmx|cut -d" " -f3 |uniq >tmp.txt
on=` ps |grep vmx|cut -d" " -f3 |uniq |wc -l`
for i in `seq 1 $on`
do
hostid=`sed -n " $i p " ./tmp.txt`
kill $hostid 1&> /dev/null
done
rm -rf ./tmp.txt
vim-cmd hostsvc/maintenance_mode_enter 1&> /dev/null
halt
fi
fi
ide
寫好腳本後,設置爲可執行權限,添加到ESXI的計劃任務程序中便可。優化
ESXI計劃任務路徑: vi /var/spool/cron/crontabs/root
spa
注意:ESXI中除了數據存儲目錄,其它目錄建立的文件,重啓後自動丟失,所以最好把腳本放存儲目錄下:/vmfs/volumes/{安裝ESXI時所取的存儲器名字}blog
更新優化版:crontab
#!/bin/sh
# author: jerry
# create:2017-8-16
# update:2020-5-28
logs='/vmfs/volumes/datastore1/log.txt'
Vmid=`vim-cmd vmsvc/getallvms|awk 'NR>1{print $1}'`
for id in $Vmid ;do
timer=`date +%F_%T`
Vmstate=`vim-cmd vmsvc/power.getstate $id |tail -1|awk '{print $2}'`
if [ "$Vmstate" == "on" ] ;then
vim-cmd vmsvc/power.shutdown $id && echo "Vmid $id At $timer Closed Successed. " >> $logs
fi
done
sleep 180
off=`esxcli vm process list|grep World|awk '{print $3}'|wc -l`
if [ $off == 0 ] ;then
vim-cmd hostsvc/maintenance_mode_enter &> /dev/null
sleep 10
halt
else
Vmid=`vim-cmd vmsvc/getallvms|awk 'NR>1{print $1}'`
for id in $Vmid ;do
timer=`date +%F_%T`
Vmstate=`vim-cmd vmsvc/power.getstate $id |tail -1|awk '{print $2}'`
if [ "$Vmstate" == "on" ] ;then
vim-cmd vmsvc/power.off $id && echo "Vmid $id At $timer By Admin Force Closed Successed. " >> $logs
fi
done
sleep 120
off=`esxcli vm process list|grep World|awk '{print $3}'|wc -l`
if [ $off == 0 ] ;then
vim-cmd hostsvc/maintenance_mode_enter &> /dev/null
sleep 10
halt
else
VmPid=`ps |grep vmx|awk '{print $2}' |uniq`
for pid in $VmPid ;do
timer=`date +%F_%T`
kill $pid 1&> /dev/null && echo "Vmid Pid $pid killed By Admin At $timer. " >> $logs
done
vim-cmd hostsvc/maintenance_mode_enter &> /dev/null
sleep 10
halt
fi
figet