Certainly! Below is a Python API that provides the functionality you've requested:
- List virtual machines in VirtualBox
- Boot a VirtualBox machine
- Simulate a click in the VM and wait for animations to stop
- Take a screenshot of the VM
The API is designed to work asynchronously using Python's asyncio library, which allows you to integrate it smoothly into an AI agent or any asynchronous codebase.
import asyncio
import subprocess
import os
import time
class VirtualBoxAPI:
def __init__(self):
pass
async def list_vms(self):
"""
List all virtual machines in VirtualBox.
"""
process = await asyncio.create_subprocess_exec(
'VBoxManage', 'list', 'vms',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if stderr:
raise Exception(f"Error listing VMs: {stderr.decode()}")
output = stdout.decode()
vms = []
for line in output.strip().split('\n'):
if line:
# Each line is in the format: '"VM name" {UUID}'
name = line.split('"')[1]
uuid = line.split('{')[1].split('}')[0]
vms.append({'name': name, 'uuid': uuid})
return vms
async def boot_vm(self, vm_name_or_uuid):
"""
Boot a virtual machine by name or UUID.
"""
process = await asyncio.create_subprocess_exec(
'VBoxManage', 'startvm', vm_name_or_uuid,
'--type', 'headless', # Change to 'gui' if you want the GUI
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if stderr and b'VBOX_E_INVALID_OBJECT_STATE' not in stderr:
# Ignore error if VM is already running
raise Exception(f"Error starting VM: {stderr.decode()}")
else:
await asyncio.sleep(5) # Wait for VM to boot up
return stdout.decode().strip()
async def click_in_vm(self, vm_name_or_uuid, x, y):
"""
Simulate a mouse click inside the VM at coordinates (x, y).
"""
# Send mouse events to the VM
# Ensure that the VM has Guest Additions installed for this to work
# Also, the VM must be running
# Move the mouse
process_move = await asyncio.create_subprocess_exec(
'VBoxManage', 'controlvm', vm_name_or_uuid,
'mousepointer', 'move', str(x), str(y),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process_move.communicate()
# Click the mouse (left button down and up)
process_click_down = await asyncio.create_subprocess_exec(
'VBoxManage', 'controlvm', vm_name_or_uuid,
'mousebutton', '1', 'down',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process_click_down.communicate()
process_click_up = await asyncio.create_subprocess_exec(
'VBoxManage', 'controlvm', vm_name_or_uuid,
'mousebutton', '1', 'up',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process_click_up.communicate()
# Optionally, wait until animations or processes complete
# This can be an arbitrary sleep, or you can implement a more robust check
await self.wait_for_vm_idle(vm_name_or_uuid)
async def wait_for_vm_idle(self, vm_name_or_uuid, timeout=10):
"""
Wait until the VM is idle by monitoring its CPU usage.
"""
end_time = time.time() + timeout
while time.time() < end_time:
# Get VM CPU usage
process = await asyncio.create_subprocess_exec(
'VBoxManage', 'metrics', 'query', vm_name_or_uuid,
'--period', '1', '--samples', '1',
'CPU/Load/User', 'CPU/Load/Kernel',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if stderr:
raise Exception(f"Error getting VM metrics: {stderr.decode()}")
output = stdout.decode()
# Parse CPU usage
cpu_usage = self.parse_cpu_usage(output)
if cpu_usage < 5: # Threshold for idle CPU usage
break
await asyncio.sleep(1)
else:
print("Warning: VM did not become idle within the timeout period.")
def parse_cpu_usage(self, metrics_output):
"""
Parse the CPU usage from VBoxManage metrics output.
"""
lines = metrics_output.strip().split('\n')
for line in lines:
if 'CPU/Load/User:' in line:
# Line format: 'CPU/Load/User: value1 value2 value3...'
parts = line.split(':')
values = parts[1].strip().split()
if values:
cpu_user_load = float(values[0])
return cpu_user_load
return 100.0 # Default high CPU usage if parsing fails
async def take_screenshot(self, vm_name_or_uuid, filename):
"""
Take a screenshot of the VM.
"""
process = await asyncio.create_subprocess_exec(
'VBoxManage', 'controlvm', vm_name_or_uuid,
'screenshotpng', filename,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if stderr:
raise Exception(f"Error taking screenshot: {stderr.decode()}")
if not os.path.isfile(filename):
raise Exception("Screenshot file was not created.")
return filename
# Example usage
async def main():
api = VirtualBoxAPI()
# List VMs
vms = await api.list_vms()
print("Available VMs:")
for vm in vms:
print(f"Name: {vm['name']}, UUID: {vm['uuid']}")
if not vms:
print("No VMs found.")
return
# Select the first VM
vm_name = vms[0]['name']
# Boot the VM
print(f"Booting VM '{vm_name}'...")
await api.boot_vm(vm_name)
# Simulate a click at position (100, 100)
print(f"Simulating click in VM '{vm_name}'...")
await api.click_in_vm(vm_name, 100, 100)
# Take a screenshot
screenshot_file = f"{vm_name}_screenshot.png"
print(f"Taking screenshot of VM '{vm_name}'...")
await api.take_screenshot(vm_name, screenshot_file)
print(f"Screenshot saved to '{screenshot_file}'.")
# Run the example if this script is executed directly
if __name__ == "__main__":
asyncio.run(main())
Explanation:
Requirements:
Asynchronous Behavior:
- The API is designed to be asynchronous to allow for non-blocking operations.
- When waiting for the VM to become idle, the
wait_for_vm_idle function uses an asynchronous loop with await asyncio.sleep(1) to avoid blocking the event loop.
Usage Example:
In the main function, the script demonstrates how to use the API:
- Lists the available VMs and selects the first one.
- Boots the selected VM.
- Simulates a click at coordinate (100, 100) inside the VM.
- Takes a screenshot of the VM and saves it to a file.
Important Notes:
- VM State Checking: Before performing operations, you may want to check if the VM is already running or in a saved state.
- Timeouts: Adjust the timeouts and thresholds (e.g., in
wait_for_vm_idle) according to the performance and behavior of your VM and the applications running inside it.
- Security: Be cautious when automating interactions with VMs, especially if they run untrusted code or contain sensitive data.
Integration with AI Agents:
- Since the API is asynchronous, it can be integrated into AI agents or systems that require non-blocking I/O operations.
- The agent can perform other tasks while awaiting the completion of VM operations.
Dependencies:
- Python 3.7+ (for
asyncio.run)
- Operating System: The script is designed for use on systems where VirtualBox and
VBoxManage are available (typically Windows, macOS, and Linux).
Further Enhancements:
- Error Handling: Implement more granular error handling and recovery strategies.
- Logging: Add logging to capture detailed information about the operations.
- Configuration: Allow configuration of timeouts, paths, and other parameters via arguments or configuration files.
- Extended Interactions: For more complex interactions with the VM, consider using VirtualBox's VRDP (VirtualBox Remote Desktop Protocol) or other remote management tools.
Please make sure to test the script in your environment and adjust parameters as needed. Let me know if you need any further assistance or modifications!