File size: 2,134 Bytes
2f582aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/bash

# Function to check for Hyper-V
check_hyperv() {
    # Check for the presence of the Hyper-V specific file system entry
    if [ -d "/sys/hypervisor/microsoft" ]; then
        echo "Hypervisor: Hyper-V"
        return 0
    fi

    # Fallback check using dmesg for "Hyper-V"
    if dmesg | grep -qi "Hyper-V"; then
        echo "Hypervisor: Hyper-V (via dmesg)"
        return 0
    fi

    # Fallback check using dmidecode (requires dmidecode to be installed and run with sudo/root)
    # Since we are in a Docker container, we'll assume a minimal environment,
    # so we'll rely on the /sys check first.
    # if sudo dmidecode -s system-product-name | grep -qi "Virtual Machine"; then
    #     if sudo dmidecode -s system-manufacturer | grep -qi "Microsoft Corporation"; then
    #         echo "Hypervisor: Hyper-V (via dmidecode)"
    #         return 0
    #     fi
    # fi

    return 1
}

# Function to check for KVM
check_kvm() {
    # Check for the presence of the KVM device file
    if [ -c "/dev/kvm" ]; then
        echo "Hypervisor: KVM (via /dev/kvm)"
        return 0
    fi

    # Check for KVM in the system product name
    if [ -f "/sys/class/dmi/id/product_name" ] && grep -qi "KVM" "/sys/class/dmi/id/product_name"; then
        echo "Hypervisor: KVM"
        return 0
    fi

    # Fallback check using dmesg for "KVM"
    if dmesg | grep -qi "KVM"; then
        echo "Hypervisor: KVM (via dmesg)"
        return 0
    fi

    return 1
}

# Main detection logic
if check_hyperv; then
    exit 0
elif check_kvm; then
    exit 0
else
    # Check for other common hypervisors as a bonus
    if [ -f "/sys/class/dmi/id/product_name" ] && grep -qi "VMware" "/sys/class/dmi/id/product_name"; then
        echo "Hypervisor: VMware"
    elif [ -f "/sys/class/dmi/id/product_name" ] && grep -qi "VirtualBox" "/sys/class/dmi/id/product_name"; then
        echo "Hypervisor: VirtualBox"
    elif [ -f "/sys/class/dmi/id/product_name" ] && grep -qi "QEMU" "/sys/class/dmi/id/product_name"; then
        echo "Hypervisor: QEMU"
    else
        echo "Hypervisor: Unknown or Bare Metal"
    fi
    exit 1
fi