python创建虚拟机,Python libvirt API-创建虚拟机

I am trying to create a python script to handle basic VM operations like: create a VM, delete a VM, start, stop, etc.

Currently I'm rather "stuck" on create

From the command line you would do something like:

qemu-img create -f qcow2 vdisk.img

virt-install --virt-type kvm --name testVM --ram 1024

--cdrom=ubuntu.iso --disk /path/to/virtual/drive,size=10,format=qcow2

--network network=default --graphics vnc,listen=0.0.0.0 --noautoconsole

--os-type=linux

And that will create a new VM called testVM and install it on the previously defined vdisk.img

But I want to do this all in python; I know how to handle the second part:

start with an XML template for the VM

open a libvirt connection and use the connection handler to create the VM

But I'm wondering about the first part, where you have to create the virtual disk.

Are there any libvirt API calls you can use?

OR, you have to put in a system call to qemu-img create to create the virtual disk?

解决方案

I finally found and answer to my problems- so I'm posting the solution here in case anyone ever hits the same problem.

The libvirt connection object can work with storage pools.

From the libvirt.org: "A storage pool is a quantity of storage set aside by an administrator, often a dedicated storage administrator, for use by virtual machines. Storage pools are divided into storage volumes either by the storage administrator or the system administrator, and the volumes are assigned to VMs as block devices."

Basically a volume is what quemu-img create creates. Once you create a storage pool in the same directory where all the .img (created using qemu-img) files are; the files created with qemu-img are seen as volumes.

The following code will list all existing volumes, including the ones created with qemu-img

conn = libvirt.open()

pools = conn.listAllStoragePools(0)

for pool in pools:

#check if pool is active

if pool.isActive() == 0:

#activate pool

pool.create()

stgvols = pool.listVolumes()

print('Storage pool: '+pool.name())

for stgvol in stgvols :

print(' Storage vol: '+stgvol)

Creating a storage pool:

def createStoragePool(conn):

xmlDesc = """

guest_images_storage_pool

8c79f996-cb2a-d24d-9822-ac7547ab2d01

4306780815

237457858

4069322956

/path/to/guest_images

0755

-1

-1

"""

pool = conn.storagePoolDefineXML(xmlDesc, 0)

#set storage pool autostart

pool.setAutostart(1)

return pool

Creating a volume:

def createStoragePoolVolume(pool, name):

stpVolXml = """

"""+name+""".img

0

10

/path/to/guest_images/"""+name+""".img

107

107

0744

virt_image_t

"""

stpVol = pool.createXML(stpVolXml, 0)

return stpVol

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值