python调用libvirt_(KVM连载) 6.1.7 libvirt API 使用示例(Python API)

该代码示例演示了如何通过libvirt Python API连接到QEMU/KVM主机并获取虚拟机的详细信息,包括名称、ID、状态、内存和vCPU数量。首先,它创建一个只读连接,然后查找并打印指定名称或ID的虚拟机信息,最后关闭连接。
摘要由CSDN通过智能技术生成

#!/usr/bin/python

# Get domain info via libvirt python API.

# Tested with python2.6 and libvirt-python-0.9.10 on a KVM host.

import libvirt

import sys

def createConnection():

conn = libvirt.openReadOnly(None)

if conn == None:

print 'Failed to open connection to QEMU/KVM'

sys.exit(1)

else:

print '-----Connection is created successfully-----'

return conn

def closeConnnection(conn):

print ''

try:

conn.close()

except:

print 'Failed to close the connection'

return 1

print 'Connection is closed'

def getDomInfoByName(conn, name):

print ''

print '----------- get domain info by name ----------"'

try:

myDom = conn.lookupByName(name)

except:

print 'Failed to find the domain with name "%s"' % name

return 1

print "Dom id: %d   name: %s" % (myDom.ID(), myDom.name())

print "Dom state: %s" % myDom.state(0)

print "Dom info: %s" % myDom.info()

print "memory: %d MB" % (myDom.maxMemory()/1024)

print "memory status: %s" % myDom.memoryStats()

print "vCPUs: %d" % myDom.maxVcpus()

def getDomInfoByID(conn, id):

print ''

print '----------- get domain info by ID ----------"'

try:

myDom = conn.lookupByID(id)

except:

print 'Failed to find the domain with ID "%d"' % id

return 1

print "Domain id is %d ; Name is %s" % (myDom.ID(), myDom.name())

if __name__ == '__main__':

name1 = "kvm-guest"

name2 = "notExist"

id1 = 3

id2 = 9999

print "---Get domain info via libvirt python API---"

conn = createConnection()

getDomInfoByName(conn, name1)

getDomInfoByName(conn, name2)

getDomInfoByID(conn, id1)

getDomInfoByID(conn, id2)

closeConnnection(conn)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值