VMCheck
Angelegt Mittwoch 04 Juni 2025
Prüfe ob eine Liste von VirtualBox VMs laufen (pingbar sind) und starte sie falls nein. Dies ist in dem Fall nützlich, wenn die VMs zwar schon gestartet sind, jedoch in der Boot-Phase hängenbleiben. Wenn der TCP Stack noch nicht gestartet wurde, antworten diese Maschinen nicht auf 'ping'. Ein simples: vboxmanage guestcontrol vmname stat /../vmname.vbox hilft hier nicht weiter.
Beispiel: monitor_vms.py Windows10
(chmod u+x monitor_vms.py)
#!/usr/bin/python3
# monitor_vms.py
# (c)2025 AMI
import subprocess
import time
import sys
def get_vm_ips():
"""
Mapping from VM names to their respective IP addresses.
This is a placeholder; replace with actual mapping or fetch mechanism.
Returns:
Mapping from VM names to their respective IP addresses.
This is a placeholder; replace with actual mapping or fetch mechanism.
Returns:
dict: Dictionary mapping VM names to their IPs.
"""
vm_ips = {
vm_ips = {
# Add more VMs as needed
'Windows10': '192.168.178.50',
'Windows10': '192.168.178.50',
}
return vm_ips
return vm_ips
def is_vm_running(vm_name, ip):
"""
Check if a VM is running and responsive using ping.
Check if a VM is running and responsive using ping.
Args:
vm_name (str): Name of the VM.
ip (str): IP address or hostname of the VM.
ip (str): IP address or hostname of the VM.
Returns:
bool: True if ping succeeds, False otherwise.
"""
try:
try:
result = subprocess.run(['ping', '-c', '1', '-W', '2', ip],
capture_output=True,
text=True,
timeout=5) # Timeout after 5 seconds
text=True,
timeout=5) # Timeout after 5 seconds
return result.returncode == 0
except subprocess.TimeoutExpired:
print(f"Ping to {vm_name} ({ip}) timed out.")
return False
return False
def start_vm(vm_name):
"""
Start a virtual machine headless using vboxmanage.
Start a virtual machine headless using vboxmanage.
Args:
vm_name (str): Name of the VM to start.
Returns:
bool: True if started successfully, False otherwise.
"""
try:
try:
result = subprocess.run(['vboxmanage', 'controlvm', vm_name, 'shutdown'],
capture_output=True,
text=True,
timeout=30)
text=True,
timeout=30)
time.sleep(60)
result = subprocess.run(['vboxmanage', 'startvm', vm_name, '--type', 'headless'],
result = subprocess.run(['vboxmanage', 'startvm', vm_name, '--type', 'headless'],
capture_output=True,
text=True,
timeout=10)
text=True,
timeout=10)
return result.returncode == 0
except subprocess.TimeoutExpired:
print(f"Starting {vm_name} timed out.")
return False
return False
def main():
if len(sys.argv) < 2:
print("Usage: python monitor_vms.py vm_name1 vm_name2 ...")
sys.exit(1)
sys.exit(1)
target_vms = sys.argv[1:]
print(f"Monitoring VMs: {', '.join(target_vms)}")
print(f"Monitoring VMs: {', '.join(target_vms)}")
# Get IP mapping for target VMs
vm_ips = get_vm_ips()
vm_ips = get_vm_ips()
# Check if all target VMs have an IP mapped
missing_ips = [vm for vm in target_vms if vm not in vm_ips]
if missing_ips:
missing_ips = [vm for vm in target_vms if vm not in vm_ips]
if missing_ips:
print(f"Missing IP information for VMs: {', '.join(missing_ips)}")
sys.exit(1)
sys.exit(1)
# First check
failed_vms = []
for vm_name in target_vms:
failed_vms = []
for vm_name in target_vms:
ip = vm_ips[vm_name]
if not is_vm_running(vm_name, ip):
if not is_vm_running(vm_name, ip):
print(f"First check: VM '{vm_name}' ({ip}) is not responding to ping.")
failed_vms.append((vm_name, ip))
failed_vms.append((vm_name, ip))
if failed_vms:
print("Waiting for 60 seconds before second check...")
time.sleep(60)
time.sleep(60)
# Second check
still_failed = []
for vm_info in failed_vms:
still_failed = []
for vm_info in failed_vms:
vm_name, ip = vm_info
if not is_vm_running(vm_name, ip):
if not is_vm_running(vm_name, ip):
print(f"Second check: VM '{vm_name}' ({ip}) is still not responding to ping.")
still_failed.append((vm_name, ip))
still_failed.append((vm_name, ip))
# Attempt to start any remaining failed VMs
if still_failed:
if still_failed:
for vm_info in still_failed:
vm_name, _ = vm_info
print(f"Attempting to start VM '{vm_name}'...")
if start_vm(vm_name):
print(f"Attempting to start VM '{vm_name}'...")
if start_vm(vm_name):
print(f"VM '{vm_name}' started successfully.")
else:
print(f"Failed to start VM '{vm_name}'.")
else:
print("All target VMs are running and responsive.")
if __name__ == "__main__":
main()