KVM—libvirt接口调用python API检查KVM域示例

查看示例
`#!/usr/bin/python

Get domain info via libvirt python API.

Tested with python2.7 and libvirt-python-2.0.0 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)`

运行程序libvirt-test.py,操作如下,输出结果为:
`[root@kvm-host kvm_demo]# python libvirt-test.py 2>/dev/null

---Get domain info via libvirt python API---
-----Connection is created successfully-----
----------- get domain info by name ----------"
Dom id: 3 name: kvm-guest
Dom state: [1, 1]
Dom info: [1, 1048576L, 1048576L, 2, 257070000000L]
memory: 1024 MB
memory status: {'actual': 1048576L, 'rss': 680228L}
vCPUs: 2
----------- get domain info by name ----------"
Failed to find the domain with name "notExist"
----------- get domain info by ID ----------"
Domain id is 3 ; Name is kvm-guest
----------- get domain info by ID ----------"
Failed to find the domain with ID "9999"
Connection is closed`

可以看到成功提取了dom的信息

posted on 2021-10-16 10:30  活儿在当下  阅读(248)  评论(0)    收藏  举报