import os def read_file(path): """Reads the content of a file, returning None if the file doesn't exist or can't be read.""" try: with open(path, 'r') as f: return f.read().strip() except (FileNotFoundError, PermissionError): return None def detect_hypervisor(): """Detects the hypervisor (Hyper-V or KVM) based on system files.""" # 1. Check for Hyper-V # The presence of this directory is a strong indicator of Hyper-V if os.path.isdir("/sys/hypervisor/microsoft"): return "Hyper-V" # 2. Check DMI information (often reliable for VMs) product_name = read_file("/sys/class/dmi/id/product_name") sys_vendor = read_file("/sys/class/dmi/id/sys_vendor") if product_name: product_name_lower = product_name.lower() if "virtualbox" in product_name_lower: return "VirtualBox" elif "vmware" in product_name_lower: return "VMware" elif "kvm" in product_name_lower or "qemu" in product_name_lower: return "KVM/QEMU" elif "microsoft corporation" in sys_vendor.lower() and "virtual machine" in product_name_lower: # Fallback for Hyper-V if /sys/hypervisor/microsoft is not present return "Hyper-V (via DMI)" # 3. Check for KVM device (requires /dev access, but worth a try) if os.path.exists("/dev/kvm"): return "KVM (via /dev/kvm)" # 4. Check for Xen (common alternative) if os.path.isdir("/sys/hypervisor/xen"): return "Xen" # 5. Check for common cloud/container environments (e.g., AWS, GCP, Docker) if sys_vendor and "amazon ec2" in sys_vendor.lower(): return "AWS EC2" if sys_vendor and "google" in sys_vendor.lower(): return "Google Compute Engine" if os.path.exists("/.dockerenv"): return "Docker Container" return "Unknown or Bare Metal" if __name__ == "__main__": hypervisor = detect_hypervisor() print(f"Hypervisor: {hypervisor}")