Skip to content

Instantly share code, notes, and snippets.

@0x3333
Last active April 9, 2024 13:38
Show Gist options
  • Save 0x3333/1d12b70034f97435bcc8ee41971a79fc to your computer and use it in GitHub Desktop.
Save 0x3333/1d12b70034f97435bcc8ee41971a79fc to your computer and use it in GitHub Desktop.
Show Memory and CPU usage of kvm vms
RAM
---
vm-1                      = 1,024 MiB
vm-2                      = 2,048 MiB

Total: 3,072 MiB

CPU(s)
------
vm-1                      = 4 cpu(s)
vm-2                      = 5 cpu(s)

Total: 9 CPU(s)
#!/bin/bash
#
# RAM
#
echo "RAM"
echo "---"
SUM=0
while read vm
do
if [ ! -z "$vm" ]; then
USED=$(($(virsh dominfo $vm | grep "Max memory" | cut -f 7 -d " ") / 1024))
printf "%-25s = %'.0f MiB\n" $vm $USED
SUM=$((SUM + USED))
fi
done < <(virsh list --all --name)
printf "\nTotal: %'.0f MiB\n\n" $SUM
#
# CPUs
#
echo "CPU(s)"
echo "------"
SUM=0
while read vm
do
if [ ! -z "$vm" ]; then
USED=$(virsh dominfo $vm | grep "CPU(s)" | cut -f 10 -d " ")
printf "%-25s = %'.0f cpu(s)\n" $vm $USED
SUM=$((SUM + USED))
fi
done < <(virsh list --all --name)
printf "\nTotal: %'.0f CPU(s)\n" $SUM
@srekkas
Copy link

srekkas commented Apr 9, 2024

Replaced cut with awk and added allocated storage. Plus count storage if multiple disks.

#!/bin/bash

printf '%-20s %3s %4s %7s %10s\n' "VM Name" "CPU" "RAM" "Storage" "Storage Allocated"

mapfile -t vm_array < <( virsh list --all --name )

while read -r vm
do
  if [ ! -z "$vm" ]; then
    CPU=$(virsh dominfo $vm | grep "CPU" | cut -f 10 -d " ")
    MEM=$(($(virsh dominfo $vm | grep "Max memory" | cut -f 7 -d " ") / 1024 / 1024))
    DSK=0
    DAL=0
    for disk in $(virsh domblkinfo $vm --all | grep "vd" | awk  '{s+=$2} END {print s}'); do
      DSK=$((DSK + disk / 1024 / 1024 / 1024))
    done
    for disk2 in $(virsh domblkinfo $vm --all | grep "vd" | awk  '{s+=$3} END {print s}'); do
      DAL=$((DAL + disk2 / 1024 / 1024 / 1024))
    done
    printf "%-20s %3s %4s %7s %10s\n" "$vm" "$CPU"  "$MEM"  "$DSK" "$DAL"
    CPU_SUM=$((CPU_SUM + CPU))
    MEM_SUM=$((MEM_SUM + MEM))
    DSK_SUM=$((DSK_SUM + DSK))
    DAL_SUM=$((DAL_SUM + DAL))
  fi
done < <( printf '%s\n' "${vm_array[@]}")

printf -- '-%.0s' {1..37}
printf '\n%-20s %3s %4s %7s %10s\n' "Totals:" "$CPU_SUM" "$MEM_SUM" "$DSK_SUM" "$DAL_SUM"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment