python xmlrpc的学习一例(获取kvm信息)
服务端代码:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import json
import libvirt
import socket
#获取本机电脑名
myname = socket.getfqdn(socket.gethostname( ))
#获取本机ip
myaddr = socket.gethostbyname(myname)
print myaddr
conn = libvirt.open("qemu:///system")
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
try:
server = SimpleXMLRPCServer((myaddr,8000),
requestHandler=RequestHandler)
except Exception,e:
print e
#server.register_instance()
server.register_introspection_functions()
def get_kvm_list():
dom = conn.listDomainsID()
return dom
def get_kvm_info(domain):
dom = conn.lookupByID(domain)
infos = dom.info()
print infos
print dom.name()
infodir = {}
infodir['id'] = domain
infodir['Name'] = dom.name()
infodir['state'] = infos[0]
infodir['MaxMemory'] = infos[1]
infodir['CPUS'] = infos[3]
infodir['CPUTIME'] = infos[2]
return infodir
server.register_function(get_kvm_list,'kvmlist')
server.register_function(get_kvm_info,'kvminfo')
server.serve_forever()
客户端代码:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import xmlrpclib
KVMhost = '192.168.0.109'
x = xmlrpclib.ServerProxy("http://%s:8000"%KVMhost)
print x.system.listMethods()
a =x.kvmlist()
print a
for i in a:
dir = x.kvminfo(i)
print "=================================================="
print "Id is :",dir['id']
print 'domain Name is :',dir['Name']
print 'State is :',dir['state']
print 'Max Memory is :', dir['MaxMemory']
print 'Num of cpu is :',dir['CPUS']
print 'Cpu time is :',dir['CPUTIME']
运行结果:
[root@c03 xmlserver]# python kvmmonitorCiletn.py
['kvminfo', 'kvmlist', 'system.listMethods', 'system.methodHelp', 'system.methodSignature']
[4, 15]
==================================================
Id is : 4
domain Name is : winxp
State is : 1
Max Memory is : 1048576
Num of cpu is : 1
Cpu time is : 1048576
==================================================
Id is : 15
domain Name is : salttest
State is : 1
Max Memory is : 1048576
Num of cpu is : 1
Cpu time is : 1048576
简单的练习下xmlrpc的使用。用来获取宿主主机上面的虚拟机的信息。打算用来集中管理kvm。:)