【问题标题】:virsh get disk location of all VMs in a Arrayvirsh 获取阵列中所有虚拟机的磁盘位置
【发布时间】:2020-01-09 18:18:50
【问题描述】:
for i in $(virsh list --all | awk '{print $2}'|grep -v Name);
  do
    virsh domblklist $i --details | awk '{print $4}'|grep -v Source;
  done

我明白了

/sdc/kvm_strage/vm1.qcow2
/sdc/kvm_strage/vm1_1.qcow2
-


/sdc/kvm_strage/vm2.qcow2
-


/sdc/kvm_strage/vm3.qcow2
/sdc/kvm_strage/vm3_1.qcow2
-

但我想获取数组中的路径并排除 "-" 之类的

my_array=(/sdc/kvm_strage/vm1.qcow2 /sdc/kvm_strage/vm1_1.qcow2 /sdc/kvm_strage/vm2.qcow2 /sdc/kvm_strage/vm3.qcow2 /sdc/kvm_strage/vm3_1.qcow2)

怎么做?

【问题讨论】:

  • virsh list --all 的输出和您想要的输出(无描述)添加到您的问题(无评论)的示例输入中。

标签: arrays bash virsh


【解决方案1】:

这是另一种方法:

declare -a my_array=($(for vm in $(virsh list --all --name); do
    virsh domblklist $vm --details | awk '/disk/{print $4}'
done))

编辑:我刚刚注意到在设置 my_array 的值时我错过了一对括号。

【讨论】:

  • 我认为您错过了从 virsh 输出中跳过的标题行。
  • 我没有。 --name 仅列出域名。
  • 非常好。有没有办法排除一些虚拟机?
  • @fteinz,您可以定义一个排除列表并检查${vm} 是否是for 循环内该列表的一部分。
【解决方案2】:

您可以使用tail --lines=+3 跳过两个标题行,以避免捕获列标题和虚线分隔标题。

这是virsh list --all 的样子:

使用tail --lines=+3 跳过2 个标题行:

 Id    Name                           State
----------------------------------------------------

要解析的数据:

 1     openbsd62                      running
 2     freebsd11-nixcraft             running
 3     fedora28-nixcraft              running

在跳过域列表的标题行后,下面的脚本会在 while read 循环中遍历每个域,女巫从 virsh list --all | tail --lines=+3 | awk '{print $2}' 接收数据

然后在while循环中,将virsh domblklist "$domain" --details | tail --lines=+3 | awk '{print $4}'的输出映射到临时文件映射数组MAPFILE
并将MAPFILE 数组条目添加到my_array

执行后,my_array 包含来自所有域的所有块设备。

#!/usr/bin/env bash

declare -a my_array=() # array of all block devices

# Iterate over domains that are read from the virsh list
while IFS= read -r domain; do
  mapfile < <( # capture devices list of domain into MAPFILE
    # Get block devices list of domain
    virsh domblklist "$domain" --details |

      # Start line 3 (skip 2 header lines)
      tail --lines=+3 |

        # Get field 4 s value
        awk '{print $4}'
  )
  my_array+=( "${MAPFILE[@]}" ) # Add the block devices paths list to my_array
done < <( # Inject list of domains to the while read loop
  # List all domains
  virsh list --all --name
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 2013-09-26
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多