Fred808 commited on
Commit
7d4caf0
·
verified ·
1 Parent(s): f6a2cdd

Upload detect_hypervisor.py

Browse files
Files changed (1) hide show
  1. detect_hypervisor.py +55 -0
detect_hypervisor.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ def read_file(path):
4
+ """Reads the content of a file, returning None if the file doesn't exist or can't be read."""
5
+ try:
6
+ with open(path, 'r') as f:
7
+ return f.read().strip()
8
+ except (FileNotFoundError, PermissionError):
9
+ return None
10
+
11
+ def detect_hypervisor():
12
+ """Detects the hypervisor (Hyper-V or KVM) based on system files."""
13
+
14
+ # 1. Check for Hyper-V
15
+ # The presence of this directory is a strong indicator of Hyper-V
16
+ if os.path.isdir("/sys/hypervisor/microsoft"):
17
+ return "Hyper-V"
18
+
19
+ # 2. Check DMI information (often reliable for VMs)
20
+ product_name = read_file("/sys/class/dmi/id/product_name")
21
+ sys_vendor = read_file("/sys/class/dmi/id/sys_vendor")
22
+
23
+ if product_name:
24
+ product_name_lower = product_name.lower()
25
+ if "virtualbox" in product_name_lower:
26
+ return "VirtualBox"
27
+ elif "vmware" in product_name_lower:
28
+ return "VMware"
29
+ elif "kvm" in product_name_lower or "qemu" in product_name_lower:
30
+ return "KVM/QEMU"
31
+ elif "microsoft corporation" in sys_vendor.lower() and "virtual machine" in product_name_lower:
32
+ # Fallback for Hyper-V if /sys/hypervisor/microsoft is not present
33
+ return "Hyper-V (via DMI)"
34
+
35
+ # 3. Check for KVM device (requires /dev access, but worth a try)
36
+ if os.path.exists("/dev/kvm"):
37
+ return "KVM (via /dev/kvm)"
38
+
39
+ # 4. Check for Xen (common alternative)
40
+ if os.path.isdir("/sys/hypervisor/xen"):
41
+ return "Xen"
42
+
43
+ # 5. Check for common cloud/container environments (e.g., AWS, GCP, Docker)
44
+ if sys_vendor and "amazon ec2" in sys_vendor.lower():
45
+ return "AWS EC2"
46
+ if sys_vendor and "google" in sys_vendor.lower():
47
+ return "Google Compute Engine"
48
+ if os.path.exists("/.dockerenv"):
49
+ return "Docker Container"
50
+
51
+ return "Unknown or Bare Metal"
52
+
53
+ if __name__ == "__main__":
54
+ hypervisor = detect_hypervisor()
55
+ print(f"Hypervisor: {hypervisor}")