首先附上libvirt-python的官方文档libvirt-python pdf 下载
需要安装libvirt-python库

1. 连接库

import sys
import libvirt

conn = libvirt.open('qemu:///system')
#conn = libvirt.openAuth(uri, auth, flags)
#conn = libvirt.openReadOnly(name)
if conn == None:
    print('Failed to open connection to qemu:///system', file=sys.stderr)
    exit(1)
conn.close()
exit(0
URL

本地连接URL有四种格式

  • driver:///system (最常用)
  • driver:///session
  • driver+unix:///system
  • driver+unix:///session

driver支持以下虚拟化
在这里插入图片描述
远程连接

driver[+transport]://[username@][hostname][:port]/[path][?extraparameters]

在这里插入图片描述

2.虚拟机管理

import sys
import libvirt

xmlconfig = '<domain>........</domain>'

conn = libvirt.open('qemu:///system')
if conn == None:
    print('Failed to open connection to qemu:///system', file=sys.stderr)
    exit(1)
#创建临时虚拟机,虚拟机关闭时会回收
#dom = conn.createXML(xmlconfig, 0)
#定义永久虚拟机
dom = conn.defineXML(xmlconfig, 0)
if dom == None:
    print('Failed to create a domain from an XML definition.', file=sys.stderr)
    exit(1)
print('Guest '+dom.name()+' has booted', file=sys.stderr)
conn.close()
exit(0)
获取虚拟机

虚拟机的三个标识符:name, id, uuid
相应地,可以通过lookupByID, lookupByName and lookupByUUID获取到某虚拟机

#example
#获取虚拟机
dom = conn.lookupByName(domainName)
#获取虚拟机主机名
name = dom.hostname()
#获取虚拟机硬件信息
state, maxmem, mem, cpus, cput = dom.info()
#获取虚拟机是否运行
flag = dom.isActive()
#设置虚拟机自启
dom.setAutostart(1)
#关闭虚拟机
dom.destroy()
#回收虚拟机
dom.undefine()

3. 存储资源池管理

默认资源池连接

#默认资源池连接
pool = conn.storagePoolLookupByName('default')
if pool == None:
    print('Failed to locate any StoragePool objects.', file=sys.stderr)
    exit(1)

创建与删除存储卷

import sys
import libvirt

stgvol_xml = """
<volume>
  <name>IMG_NAME</name>
  <capacity unit="G">SIZE</capacity>
  <target>
    <path>IMG_PATH</path>
    <format type='qcow2'/>
    <permissions>
      <owner>107</owner>
      <group>107</group>
      <mode>0744</mode>
      <label>virt_image_t</label>
    </permissions>
  </target>
</volume>"""

pool = 'default'
conn = libvirt.open('qemu:///system')
if conn == None:
    print('Failed to open connection to qemu:///system', file=sys.stderr)
    exit(1)
pool = conn.storagePoolLookupByName(pool)
if pool == None:
    print('Failed to locate any StoragePool objects.', file=sys.stderr)
    exit(1)
#创建存储卷
stgvol = pool.createXML(stgvol_xml, 0)
if stgvol == None:
    print('Failed to create a  StorageVol objects.', file=sys.stderr)
    exit(1)
# remove the storage volume
# physically remove the storage volume from the underlying disk media
stgvol.wipe(0)
# logically remove the storage volume from the storage pool
stgvol.delete(0)
conn.close()
exit(0)

更多详情请参考官方文档

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐