提问人:dija 提问时间:6/28/2023 更新时间:7/3/2023 访问量:129
使用 Libvirt 和 KVM 创建 VM
Create VM Using Libvirt & KVM
问:
我正在尝试在 Ubuntu 上使用 libvirt 和 KVM(安装在 VM 工作站中)创建虚拟机。我的目标是使用 Python 和 libvirt 库以编程方式创建、启动、停止和删除虚拟机。
这是我的代码:
import libvirt
def create_vm(name, memory):
conn = libvirt.open()
if conn is None:
print('Failed to connect to the hypervisor')
return
try:
# Check if the virtual machine already exists
if conn.lookupByName(name):
print(f'Virtual machine {name} already exists')
return
# Create the virtual machine
xmlconfig = f'''
<domain type='kvm'>
<name>{name}</name>
<memory unit='KiB'>{memory}</memory>
<vcpu placement='static'>1</vcpu>
<os>
<type arch='x86_64' machine='pc-i440fx-2.12'>hvm</type>
<boot dev='hd'/>
</os>
<devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/var/lib/libvirt/images/disk_image.qcow2'/>
<target dev='vda' bus='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
</disk>
<interface type='network'>
<mac address='52:54:00:aa:bb:cc'/>
<source network='default'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>
</devices>
</domain>
'''
conn.createXML(xmlconfig, 0)
print(f'Virtual machine {name} created successfully')
except libvirt.libvirtError as e:
print(f'Failed to create virtual machine: {str(e)}')
conn.close()
# Usage example
create_vm('my_vm', 1024)
但是,当我运行代码时,出现以下错误:
libvirt: QEMU Driver error: Domain not found: no domain with matching name 'my_vm'
Failed to create virtual machine: Domain not found: no domain with matching name 'my_vm'
我已经安装并配置了 libvirt,并验证了我的物理机上是否启用了虚拟化。
有人可以帮我了解可能导致此错误的原因以及如何使用 libvirt 和 KVM 成功创建虚拟机吗?
提前感谢您的帮助。
答:
0赞
DanielB
7/3/2023
#1
你正在检查 的返回值 to detect missing VM,但当请求的 VM 不存在时,此方法会引发异常。所以你需要一个块来代替。lookupByName
try/except
评论