diff options
| author | Your Name <you@example.com> | 2024-12-29 20:10:29 +0800 |
|---|---|---|
| committer | Your Name <you@example.com> | 2024-12-29 20:10:29 +0800 |
| commit | 6f49e7a01ed42cb1227e5070f5d1095342e9bc29 (patch) | |
| tree | d7f46b53cdd0b0ea70855c364ee5f4f58521923b /others/vm3/compute/ls.sh | |
| parent | 26d1a94dfd4eeb91b259bfd9d4b8f8d1cdfabd98 (diff) | |
debian12-support
Diffstat (limited to 'others/vm3/compute/ls.sh')
| -rwxr-xr-x | others/vm3/compute/ls.sh | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/others/vm3/compute/ls.sh b/others/vm3/compute/ls.sh new file mode 100755 index 0000000..b62ef14 --- /dev/null +++ b/others/vm3/compute/ls.sh @@ -0,0 +1,45 @@ + +#!/bin/bash +printf "%-10s %-15s %-8s %-6s %-8s %-12s %-10s\n" "Network" "IP" "State" "vCPUs" "RAM(GB)" "Disk(GB)" "Name" +printf "%-10s %-15s %-8s %-6s %-8s %-12s %-10s\n" "----------" "---------------" "--------" "-----" "-------" "-----------" "----------" + +# Get all VMs +vms=$(sudo virsh list --name --all) + +# Cache the network leases once +default_leases=$(sudo virsh net-dhcp-leases default 2>/dev/null) + +for vm in $vms; do + # Get XML once and use it multiple times + xml=$(sudo virsh dumpxml "$vm" 2>/dev/null) + + # Extract all data from the cached XML + mac=$(echo "$xml" | grep "mac address" | awk -F\' '{ print $2}') + net=$(echo "$xml" | grep "<source network" | awk -F\' '{print $2}') + if [ -z "$net" ]; then + net="default" + fi + + # Use cached leases + ip=$(echo "$default_leases" | grep "$mac" | awk '{print $5}' | cut -f1 -d'/') + + # Run commands in background and save to temp files + sudo virsh domstate "$vm" 2>/dev/null > /tmp/state.$$ & + echo "$xml" | grep "<vcpu" | awk -F'[<>]' '{print $3}' > /tmp/vcpus.$$ & + echo "$xml" | grep "<memory" | awk -F'[<>]' '{print $3}' | awk '{ printf "%.2f", $1/1048576 }' > /tmp/ram.$$ & + sudo du -sk "/var/lib/libvirt/images/${vm}/${vm}.qcow2" 2>/dev/null | awk '{ printf "%.2f", $1/1024/1024 }' > /tmp/disk.$$ & + + wait + + # Read from temp files + state=$(cat /tmp/state.$$ 2>/dev/null) + vcpus=$(cat /tmp/vcpus.$$ 2>/dev/null) + ram=$(cat /tmp/ram.$$ 2>/dev/null) + disk=$(cat /tmp/disk.$$ 2>/dev/null) + + # Clean up temp files + rm -f /tmp/state.$$ /tmp/vcpus.$$ /tmp/ram.$$ /tmp/disk.$$ + + printf "%-10s %-15s %-8s %-6s %-8s %-12s %-10s\n" \ + "$net" "$ip" "$state" "$vcpus" "$ram" "$disk" "$vm" +done |
