[注意:无需使用任何虚拟化 API 即可实现自动化。从我的博客文章 http://db42.wordpress.com/2011/10/14/guest-automation-with-qemukvm/.]
Step 1:
默认情况下,QEMU 使用 SDL 显示 VGA 输出。因此,第一步是通过标准 I/O 与 QEMU 进行交互。 QEMU 为此提供了一个选项。
来自 QEMU 文档:
- 图形学通常,QEMU 使用 SDL 来显示 VGA 输出。使用此选项,您可以完全禁用图形输出,以便 QEMU
一个简单的命令行应用程序。仿真的串口是
在控制台上重定向。因此,仍然可以使用QEMU来调试
带有串行控制台的 Linux 内核。
因此,您所要做的就是调用 QEMU-nographic
.
qemu -nographic -hda guest.disk
Step 2:
现在您可以通过命令行与来宾(或 QEMU 进程)进行交互,您必须自动执行此交互。在 python 中执行此操作的明显方法是启动 QEMU 进程(使用-nographic
) with 子流程模块 http://jimmyg.org/blog/2009/working-with-python-subprocess.html然后与该进程进行通信。但令我惊讶的是,这对我来说不起作用。所以,我寻找其他方法。
后来我发现,做这类工作最棒的工具是Expect http://en.wikipedia.org/wiki/Expect。它是用 TCL 编写的交互式应用程序的自动化工具。
本指南 http://www.linuxjournal.com/article/3065应该可以帮助您开始使用 Expect。以下是使用 Expect 运行 QEMU 来宾的脚本。
#!/usr/bin/expect -f
#starts guest vm, run benchmarks, poweroff
set timeout -1
#Assign a variable to the log file
set log [lindex $argv 0]
#Start the guest VM
spawn qemu -nographic -hda guest.disk
#Login process
expect "login: "
#Enter username
send "user\r"
#Enter Password
expect "Password: "
send "user\r"
#Do whatever you want to do with in the guest VM. ( Run a process and write result to log )
#poweroff the Guest VM
expect "# "
send "shutdown -h now\r"