如何写一个脚本运行虚拟机

wen 实用脚本 3

本文目录导读:

如何写一个脚本运行虚拟机

  1. 使用 VirtualBox 的 VBoxManage
  2. 使用 VMware 的 vmrun
  3. 使用 QEMU/KVM 的 virsh
  4. 使用批处理脚本 (Windows)
  5. 使用示例
  6. 注意事项

我来介绍几种常见的方法来编写脚本运行虚拟机。

使用 VirtualBox 的 VBoxManage

Bash 脚本示例

#!/bin/bash
# 虚拟机名称
VM_NAME="Ubuntu_20.04"
# 启动虚拟机(无界面模式)
start_vm() {
    echo "正在启动虚拟机: $VM_NAME"
    VBoxManage startvm "$VM_NAME" --type headless
}
# 启动虚拟机(有界面模式)
start_vm_gui() {
    echo "正在启动虚拟机: $VM_NAME (GUI模式)"
    VBoxManage startvm "$VM_NAME" --type gui
}
# 停止虚拟机
stop_vm() {
    echo "正在关闭虚拟机: $VM_NAME"
    VBoxManage controlvm "$VM_NAME" poweroff
}
# 保存虚拟机状态
save_vm() {
    echo "正在保存虚拟机状态: $VM_NAME"
    VBoxManage controlvm "$VM_NAME" savestate
}
# 主程序
case "$1" in
    start)
        start_vm
        ;;
    start-gui)
        start_vm_gui
        ;;
    stop)
        stop_vm
        ;;
    save)
        save_vm
        ;;
    *)
        echo "用法: $0 {start|start-gui|stop|save}"
        exit 1
        ;;
esac

使用 VMware 的 vmrun

PowerShell 脚本示例 (Windows)

# VMware 虚拟机管理脚本
param(
    [Parameter(Mandatory=$true)]
    [ValidateSet("start", "stop", "restart", "status")]
    [string]$Action,
    [string]$VMXPath = "C:\VMs\Windows10\Windows10.vmx"
)
# 设置 vmrun 路径
$vmrunPath = "C:\Program Files (x86)\VMware\VMware VIX\vmrun.exe"
switch ($Action) {
    "start" {
        Write-Host "启动虚拟机..."
        & $vmrunPath start "$VMXPath" nogui
    }
    "stop" {
        Write-Host "关闭虚拟机..."
        & $vmrunPath stop "$VMXPath" hard
    }
    "restart" {
        Write-Host "重启虚拟机..."
        & $vmrunPath reset "$VMXPath" hard
    }
    "status" {
        & $vmrunPath list
    }
}

使用 QEMU/KVM 的 virsh

完整的 Python 脚本示例

#!/usr/bin/env python3
import subprocess
import sys
import argparse
class VMManager:
    def __init__(self, vm_name):
        self.vm_name = vm_name
        self.virsh_cmd = "virsh"
    def start_vm(self, autostart=False):
        """启动虚拟机"""
        try:
            cmd = [self.virsh_cmd, "start", self.vm_name]
            if autostart:
                cmd.append("--autostart")
            result = subprocess.run(cmd, capture_output=True, text=True, check=True)
            print(f"虚拟机 {self.vm_name} 启动成功")
            return True
        except subprocess.CalledProcessError as e:
            print(f"启动失败: {e.stderr}")
            return False
    def stop_vm(self, force=False):
        """停止虚拟机"""
        try:
            cmd = [self.virsh_cmd, "shutdown", self.vm_name]
            if force:
                cmd = [self.virsh_cmd, "destroy", self.vm_name]
            result = subprocess.run(cmd, capture_output=True, text=True, check=True)
            print(f"虚拟机 {self.vm_name} 已停止")
            return True
        except subprocess.CalledProcessError as e:
            print(f"停止失败: {e.stderr}")
            return False
    def get_status(self):
        """获取虚拟机状态"""
        try:
            result = subprocess.run(
                [self.virsh_cmd, "domstate", self.vm_name],
                capture_output=True, text=True, check=True
            )
            return result.stdout.strip()
        except subprocess.CalledProcessError:
            return "unknown"
    def list_all_vms(self):
        """列出所有虚拟机"""
        try:
            result = subprocess.run(
                [self.virsh_cmd, "list", "--all"],
                capture_output=True, text=True, check=True
            )
            print("当前虚拟机列表:")
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"查询失败: {e.stderr}")
def main():
    parser = argparse.ArgumentParser(description="虚拟机管理脚本")
    parser.add_argument("action", choices=["start", "stop", "status", "list"],
                      help="操作类型")
    parser.add_argument("--name", "-n", help="虚拟机名称")
    parser.add_argument("--force", "-f", action="store_true",
                      help="强制操作")
    args = parser.parse_args()
    if args.action == "list":
        # 列出所有虚拟机不需要名称
        manager = VMManager("")
        manager.list_all_vms()
        return
    if not args.name:
        print("错误: 需要指定虚拟机名称 (--name)")
        sys.exit(1)
    manager = VMManager(args.name)
    if args.action == "start":
        manager.start_vm()
    elif args.action == "stop":
        manager.stop_vm(args.force)
    elif args.action == "status":
        status = manager.get_status()
        print(f"虚拟机 {args.name} 状态: {status}")
if __name__ == "__main__":
    main()

使用批处理脚本 (Windows)

@echo off
setlocal enabledelayedexpansion
REM 虚拟机名称
set VM_NAME=Ubuntu_20.04
REM 检查参数
if "%1"=="" (
    echo 用法: %0 {start^|stop^|save}
    goto :eof
)
REM 虚拟机操作
if /i "%1"=="start" (
    echo 正在启动虚拟机: %VM_NAME%
    "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" startvm "%VM_NAME%" --type headless
) else if /i "%1"=="stop" (
    echo 正在关闭虚拟机: %VM_NAME%
    "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "%VM_NAME%" poweroff
) else if /i "%1"=="save" (
    echo 正在保存虚拟机状态: %VM_NAME%
    "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "%VM_NAME%" savestate
) else (
    echo 无效参数: %1
    echo 用法: %0 {start^|stop^|save}
)
endlocal

使用示例

VirtualBox (Linux/Mac)

# 使脚本可执行
chmod +x vm_manager.sh
# 启动虚拟机
./vm_manager.sh start
# 停止虚拟机
./vm_manager.sh stop

KVM (Python脚本)

# 启动虚拟机
python vm_manager.py start --name ubuntu_vm
# 停止虚拟机(强制)
python vm_manager.py stop --name ubuntu_vm --force
# 查看状态
python vm_manager.py status --name ubuntu_vm
# 列出所有虚拟机
python vm_manager.py list

注意事项

  1. 权限问题: 某些虚拟化软件需要管理员权限运行
  2. 路径设置: 确保虚拟机路径正确
  3. 依赖检查: 确保相应的虚拟化工具已安装
  4. 错误处理: 添加适当的错误处理和日志记录
  5. 安全考虑: 不要在脚本中硬编码敏感信息

选择哪种方式取决于你使用的虚拟化平台和操作系统,建议先从简单的脚本开始,逐步添加更多功能。

抱歉,评论功能暂时关闭!