基于python调用libvirt API
1、程序代码
#!/usr/bin/python
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 closeConnection(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.memoryStatus()
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)
closeConnection(conn)
2、运行,结果如图1所示
python libvirt-test.py 2>/dev/null
图 1
3、中间过程错误说明
执行运行命令时出现如图2所示的错误
图 2
本文实验环境是利用编译安装的qemu和libvirt,没有安装libvirt-python的依赖包,所以需要python官网上下载相应的包,下载链接如下
https://pypi.python.org/pypi/libvirt-python/3.10.0
下载后解压编译安装,操作如下
tar -zxvf libvirt-python-3.10.0.tar.gz
python setup.py build
python setup.py install
安装完成后,查看/usr/local/lib/python2.7/dist-packages/目录下是否有相应的包,如图3所示
图 3
即可继续执行步骤2中的指令即可得到相应运行结果。