ESXI Auto PowerOff

2023-08-23 14:53:48 浏览数 (2)

/vmfs/volumes/Data/autoPowerOff.sh

代码语言:javascript复制
#!/usr/bin/env sh

# 如果有虚拟机还在运行,则退出
for ID in $(vim-cmd vmsvc/getallvms | grep -vE '(iKuai|OpenWrt|Vmid)' | awk '{print $1}'); do
  if vim-cmd vmsvc/power.getstate ${ID} | grep -q "Powered on"; then
    echo "当前还有虚拟机在运行 ID: ${ID}"
    exit 0
  fi
done

# 否则关闭虚拟机
for ID in $(vim-cmd vmsvc/getallvms | grep -v 'Vmid' | awk '{print $1}'); do
  if vim-cmd vmsvc/power.getstate ${ID} | grep -q "Powered on"; then
    echo "关闭虚拟机 ID: ${ID}"
    if ! vim-cmd vmsvc/power.shutdown "${ID}"; then
      echo "强制关闭虚拟机 ID: ${ID}"
      vim-cmd vmsvc/power.off "${ID}"
    fi
  fi
done

# 关闭ESXi
echo "已关闭全部虚拟机,即将关机"
esxcli system maintenanceMode set --enable true
esxcli system shutdown poweroff --reason "no vm Runing!" --delay 300
esxcli system maintenanceMode set --enable false

修改权限

代码语言:javascript复制
chmod  x /vmfs/volumes/Data/autoPowerOff.sh

/etc/rc.local.d/local.sh

代码语言:javascript复制
#!/bin/sh   group=host/vim/vmvisor/boot

# local configuration options

# Note: modify at your own risk!  If you do/use anything in this
# script that is not part of a stable API (relying on files to be in
# specific places, specific tools, specific output, etc) there is a
# possibility you will end up with a broken system after patching or
# upgrading.  Changes are not supported unless under direction of
# VMware support.

# Note: This script will not be run when UEFI secure boot is enabled.

#关闭cron进程(关闭进程后修改计划任务root文件)
/bin/kill $(cat /var/run/crond.pid)

#向/var/spool/crontab/root里添加关闭虚拟机、关机的计划任务
/bin/echo '*/30 *    *   *   *   /vmfs/volumes/Data/autoPowerOff.sh' >> /var/spool/cron/crontabs/root

#重启cron进程(将加载修改后的root文件)
/usr/lib/vmware/busybox/bin/busybox crond

exit 0

保存开机自动命令设置

代码语言:javascript复制
/sbin/auto-backup.sh

立即刷新

代码语言:javascript复制
/bin/kill $(cat /var/run/crond.pid)
/bin/echo '*/30 *    *   *   *   /vmfs/volumes/Data/autoPowerOff.sh' >> /var/spool/cron/crontabs/root
/usr/lib/vmware/busybox/bin/busybox crond

查看是否生效

代码语言:javascript复制
cat /var/spool/cron/crontabs/root

Thanks

  • https://anby.org/index.php/archives/182/

XRSec has the right to modify and interpret this article. If you want to reprint or disseminate this article, you must ensure the integrity of this article, including all contents such as copyright notice. Without the permission of the author, the content of this article shall not be modified or increased or decreased arbitrarily, and it shall not be used for commercial purposes in any way

0 人点赞