环境中有多个cloudstack构建了多个vdc,想通过脚本来获取资源信息并作为报表发送到邮件
下面是一个简化版的思路:
1、构建配置文件
这里用xml文件来存放这些cloudstack的信息,如下:
cloudstack1 172.16.2.33 cloudstack2 172.16.2.56 cloudstack1 172.16.2.78 cloudstack2 172.16.2.98
2、实现远程执行代码模块
cat sshLib.py #!/usr/bin/env python import paramiko import json def connect(host,user='test',pwd='test'): 'this is use the paramiko connect the host,return conn' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host,username=user,password=pwd,allow_agent=True) return ssh except: return None def exec_commands(conn,cmd): 'this is use the conn to excute the cmd and return the results of excute the command' stdin,stdout,stderr = conn.exec_command(cmd) results=stdout.read() return results def copy_moddule(conn,inpath,outpath): 'this is copy the module to the remote server' ftp = conn.open_sftp() ftp.put(inpath,outpath) ftp.close() return outpath def excutor(host,outpath,args): conn = connect(host) if not conn: return [host,None] cmd =command(args,outpath) result = exec_commands(conn,cmd) print '%r' % result result = json.loads(result) return [host,result] if __name__ == '__main__': print exec_commands(connect('172.16.2.78'),'/usr/bin/cloudmonkey list hosts type=Routing filter=clustername,zonename,name,ipaddress,state,cpuallocated,cpuused,memoryused | sed \'1,2d\'') #excutor('172.16.2.78','ls','/home/test/temp/')
3、编写获取cloudstack信息模块
cat csInfoLib.py #!/usr/bin/env python import os,sys import logging sys.path.append("/home/test/cbin/script/lib/") import json import sshLib logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='//home/clouder/temp/test.log', filemode='w') class Base: def getJsonInfo(self,comm,host,user='test',pwd='test'): '''get infomation as json mode''' #exc_res = os.popen(comm).read() exc_res = sshLib.exec_commands(sshLib.connect(host,user,pwd),comm) logging.debug("%s" % exc_res) return json.loads(exc_res) def getViewInfo(self,comm,host,user='test',pwd='test'): '''get information to view''' return sshLib.exec_commands(sshLib.connect(host,user,pwd),comm) def printInfo(self,other,info): print other+"\n"+info class CloudstackInfo(Base): def __init__(self,satellite,name,ip): self.satellite = satellite self.name = name self.ip = ip self.user = 'clouder' self.pwd = 'engine' self.types_dic = { 0: 'Memery',1: 'CPU',3:'Running Vm Storage',4:'Public Ip',5:'Manage Ip',7:'Vlan',9:'Local Storage',8:'Share Network Ip',6:'Secondary Storage',2:'Allocated Vm Storage',19:'GPU'} self.zone_attr_list = ['capacityused','capacitytotal','percentused','type','zonename'] self.host_attr_list = ['clustername','zonename','name','ipaddress','state','cpuallocated','cpuused','memoryused'] self.svm_attr_list = ['name','systemvmtype','zonename','state','publicip','gateway'] self.zone_json_comm = 'export TERM=vt100;/usr/bin/cloudmonkey -d json list capacity filter=capacityused,capacitytotal,percentused,type,zonename' self.zone_view_comm = 'export TERM=vt100;/usr/bin/cloudmonkey list capacity filter=capacityused,capacitytotal,percentused,type,zonename sortby=usage| sed \'1,2d\'' self.host_json_comm = 'export TERM=vt100;/usr/bin/cloudmonkey -d json list hosts type=Routing filter=clustername,zonename,name,ipaddress,state,cpuallocated,cpuused,memoryused' self.host_view_comm = 'export TERM=vt100;/usr/bin/cloudmonkey list hosts type=Routing filter=clustername,zonename,name,ipaddress,state,cpuallocated,cpuused,memoryused | sed \'1,2d\'' self.svm_json_comm = 'export TERM=vt100;/usr/bin/cloudmonkey -d json list systemvms' self.svm_view_comm = 'export TERM=vt100;/usr/bin/cloudmonkey list systemvms filter=name,systemvmtype,zonename,state,publicip,gateway sortby=zonename | sed \'1,2d\'' def getZoneJson(self): info = self.getJsonInfo(self.zone_json_comm,self.ip,self.user,self.pwd)['capacity'] for item in info: item['type'] = self.types_dic[item['type']] return info def getHostJson(self): return self.getJsonInfo(self.host_json_comm,self.ip,self.user,self.pwd)['host'] def getSvmJson(self): return self.getJsonInfo(self.svm_json_comm,self.ip,self.user,self.pwd)['systemvm'] def printZoneView(self): disc_str = "zone info(%s:%s)" % (self.satellite,self.name) self.printInfo(disc_str,self.getViewInfo(self.zone_view_comm,self.ip)) def printHostView(self): disc_str = "host info(%s:%s)" % (self.satellite,self.name) self.printInfo(disc_str,self.getViewInfo(self.host_view_comm,self.ip)) def printSystemVmView(self): disc_str = "systemVmInfo info(%s:%s)" % (self.satellite,self.name) self.printInfo(disc_str,self.getViewInfo(self.svm_view_comm,self.ip)) def printAll(self): self.printZoneView() self.printHostView() self.printSystemVmView() if __name__ == '__main__': info = CloudstackInfo('bjvdc','cloudstack1','172.16.2.78') info.printZoneView() info.printHostView() info.printSystemVmView()
4、格式化输出为html
cat infoOutput.py #!/usr/bin/env python import sys import xml.etree.ElementTree as ET sys.path.append("/home/test/cbin/script/lib/") from csInfoLib import CloudstackInfo def csBaseInfo(): cs_xml = '/home/test/cbin/script/conf/cs.xml' cs_tree = ET.parse(cs_xml) cs_tree_root = cs_tree.getroot() evi_dic = {} for evi in cs_tree_root.findall('environment'): prp_list = [] for prp in evi.findall('property'): prp_dic = {} prp_dic['name'] = prp.find('name').text prp_dic['ipaddress'] = prp.find('ipaddress').text prp_list.append(prp_dic) evi_dic[evi.attrib['satellite']] = prp_list return evi_dic def createHtml(tr_list,source_list): html_start = "