开启 SSH

主机-操作-服务-启用 Secure Shell (SSH)

登录 SSH 终端

使用你喜欢的 SSH 软件登录 ESXi。

编写关机脚本文件

进入存储空间目录

关机脚本文件需放到存储目录中,否则 ESXi 重启会丢失配置的文件。

1
cd /vmfs/volumes/datastore1

编辑关机脚本文件

1
2
3
mkdir script  # 创建脚本文件存放目录
cd script
vi poweroff.sh

在编辑框输入以下内容并保存退出:

1
2
3
4
5
6
7
8
9
10
#!/bin/sh

#shutdown all VMs(2,3,9 is VMID,add your VMIDs here)
#vim-cmd vmsvc/power.shutdown 1
#vim-cmd vmsvc/power.off 1
#vim-cmd vmsvc/power.shutdown 2
#vim-cmd vmsvc/power.off 2

#Poweroff Host
/sbin/poweroff

前面注释的代码用于关闭虚拟机。
我在各个虚拟机中配置了自动关机,因此注释。

设置脚本权限为 755:

1
chmod 755 poweroff.sh

ps:上述命令中,7 代表文件拥有者的权限,5 分别代表组用户和其他用户的权限;755 即是 owner-read-write-execute,group-read-execute,others-read-execute,即执行者可读、写、执行文件权限,同组用户可读、可执行,其他用户可读、可执行。Linux 755 权限通过权限限制,使普通用户无法访问、修改、删除系统核心文件,并确保特定用户可以访问特定文件,确保服务器的安全性。此外,在用户登录系统时,也可以设置 755 的权限,以便只允许特定人员登录服务器,减少外来攻击的可能性。

增加启动项目

打开自启动文件:

1
vi /etc/rc.local.d/local.sh

在文件末尾的 exit 0 前面增加自动关机计划任务,编辑后的文件如下所示:

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
#!/bin/sh

# local configuration options
#
# file: /etc/rc.local.d/local.sh
#
# 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.

# 复制中国时区文件
cp -f /vmfs/volumes/datastore1/script/Shanghai /etc/localtime

# 增加自动关机计划任务
/bin/kill $(cat /var/run/crond.pid)
# crontabs format: min hour day mon dow command
/bin/echo '0 1 * * * /vmfs/volumes/datastore1/script/poweroff.sh' >> /var/spool/cron/crontabs/root
/usr/lib/vmware/busybox/bin/busybox crond

exit 0
  • 自动关机脚本是为了在 ESXi 启动后将 cron 设定的信息写入到 crontab 的配置文件中,并重启 cron 进程。
  • 复制中国时区文件(此文件可以从其它 Linux 系统中复制)是为了解决 ESXi 时区问题。如果不复制该文件 ESXi 使用的是 UTC 时间,设定计划任务的时间需要减去 8 小时才是 UTC 时间。例如:23:00 的计划任务需为 “0 15 * * *”。

备份启动脚本

前面已经提到 ESXi 重启会重置系统,因此需要备份启动脚本。

1
 auto-backup.sh

ps:该脚本系统自带,直接执行接口。

配置立即生效

执行编辑好的启动脚本文件即可。

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