用于判断当前Linux系统的虚拟化,最后输出数值在变量virtual中,如果无法判断,则输出Dedicated(专用),代码如下:

virt_check(){
    if hash ifconfig 2>/dev/null; then
        eth=$(ifconfig)
    fi

    virtualx=$(dmesg) 2>/dev/null
    
    if  [[ "$(command -v dmidecode)" == "" ]]; then
        echo " Installing Dmidecode ..."
        if [[ ! -z "$(type -p yum)" ]]; then
            yum -y install dmidecode > /dev/null 2>&1
        else
            apt-get update > /dev/null 2>&1
            apt-get -y install dmidecode > /dev/null 2>&1
        fi
    fi

    if  [[ "$(command -v dmidecode)" != ""  ]]; then
        sys_manu=$(dmidecode -s system-manufacturer) 2>/dev/null
        sys_product=$(dmidecode -s system-product-name) 2>/dev/null
        sys_ver=$(dmidecode -s system-version) 2>/dev/null
    else
        sys_manu=""
        sys_product=""
        sys_ver=""
    fi
    
    if grep docker /proc/1/cgroup -qa; then
        virtual="Docker"
    elif grep lxc /proc/1/cgroup -qa; then
        virtual="Lxc"
    elif grep -qa container=lxc /proc/1/environ; then
        virtual="Lxc"
    elif [[ -f /proc/user_beancounters ]]; then
        virtual="OpenVZ"
    elif [[ "$virtualx" == *kvm-clock* ]]; then
        virtual="KVM"
    elif [[ "$cname" == *KVM* ]]; then
        virtual="KVM"
    elif [[ "$cname" == *QEMU* ]]; then
        virtual="KVM"
    elif [[ "$virtualx" == *"VMware Virtual Platform"* ]]; then
        virtual="VMware"
    elif [[ "$virtualx" == *"Parallels Software International"* ]]; then
        virtual="Parallels"
    elif [[ "$virtualx" == *VirtualBox* ]]; then
        virtual="VirtualBox"
    elif [[ -e /proc/xen ]]; then
        virtual="Xen"
    elif [[ "$sys_manu" == *"Microsoft Corporation"* ]]; then
        if [[ "$sys_product" == *"Virtual Machine"* ]]; then
            if [[ "$sys_ver" == *"7.0"* || "$sys_ver" == *"Hyper-V" ]]; then
                virtual="Hyper-V"
            else
                virtual="Microsoft Virtual Machine"
            fi
        fi
    else
        virtual="Dedicated"
    fi
}
最后修改:2023 年 03 月 05 日
如果觉得我的文章对你有用,请随意赞赏