You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写脚本解析ESXI vim-cmd输出,获取指定VM ID的stopDelay参数值

问题

我有一个UPS供电时ESXi主机的关机脚本,现在想优化它,让它能读取ESXi主机UI里设置的stopDelay参数。这个参数可以通过控制台命令vim-cmd hostsvc/autostartmanager/get_autostartseq获取。需要写一个脚本,接收VM ID作为输入参数,返回对应VM的stopDelay值。

命令输出示例:

[root@localhost:~] vim-cmd hostsvc/autostartmanager/get_autostartseq

(vim.host.AutoStartManager.AutoPowerInfo) [
   (vim.host.AutoStartManager.AutoPowerInfo) {
      key = 'vim.VirtualMachine:1',
      startOrder = 1,
      startDelay = 10,
      waitForHeartbeat = "systemDefault",
      startAction = "powerOn",
      stopDelay = 13,
      stopAction = "systemDefault"
   },
   (vim.host.AutoStartManager.AutoPowerInfo) {
      key = 'vim.VirtualMachine:2',
      startOrder = 2,
      startDelay = -1,
      waitForHeartbeat = "systemDefault",
      startAction = "powerOn",
      stopDelay = 5,
      stopAction = "systemDefault"
   },
   (vim.host.AutoStartManager.AutoPowerInfo) {
      key = 'vim.VirtualMachine:3',
      startOrder = 3,
      startDelay = -1,
      waitForHeartbeat = "systemDefault",
      startAction = "powerOn",
      stopDelay = -1,
      stopAction = "systemDefault"
   }
]

脚本调用要求:

  • ./getVMStopDelay 1 返回 13
  • ./getVMStopDelay 2 返回 5
  • ./getVMStopDelay 3 返回 -1

解决方案

可以用Bash脚本结合awk工具解析命令输出,精准匹配目标VM ID对应的stopDelay值。以下是完整实现脚本:

#!/bin/bash

# 检查参数数量是否正确
if [ $# -ne 1 ]; then
    echo "用法: $0 <VM_ID>"
    exit 1
fi

TARGET_VM=$1

# 调用vim-cmd并解析输出
vim-cmd hostsvc/autostartmanager/get_autostartseq | awk -v vm="$TARGET_VM" '
    /key = '\''vim.VirtualMachine:/ {
        # 提取VM ID并清理多余字符
        current_vid = substr($4, 18)
        gsub(/'\'',/, "", current_vid)
        found = (current_vid == vm) ? 1 : 0
    }
    found && /stopDelay =/ {
        print $3
        exit
    }
'

脚本说明:

  1. 参数校验:首先判断是否传入了正确数量的参数,未传入则输出用法并退出。
  2. 输出解析逻辑:
    • 匹配包含VM标识的行,提取其中的ID号并清理引号、逗号等无关字符。
    • 当匹配到目标VM ID时,标记进入匹配状态。
    • 在匹配状态下找到stopDelay行,直接输出对应数值并终止脚本,避免多余计算。

使用步骤:

  1. 将脚本保存为getVMStopDelay文件。
  2. 赋予执行权限:chmod +x getVMStopDelay。
  3. 按需求调用:./getVMStopDelay <目标VM ID>。

内容的提问来源于stack exchange,提问作者user2014521

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:04:57