腳本實現獲取cloudstack中資源和一些狀態信息以html報表顯示

環境中有多個cloudstack構建了多個vdc,想通過腳本來獲取資源信息並作爲報表發送到郵件

下面是一個簡化版的思路:

1、構建配置文件

這裏用xml文件來存放這些cloudstack的信息,如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration>
	<environment satellite="gzvdc">
		<property>
			<name>cloudstack1</name>
			<ipaddress>172.16.2.33</ipaddress>
		</property>
		<property>
                        <name>cloudstack2</name>
                        <ipaddress>172.16.2.56</ipaddress>
                </property>
	</environment>
	<environment satellite="bjvdc">
		<property>
                        <name>cloudstack1</name>
                        <ipaddress>172.16.2.78</ipaddress>
                </property>
                <property>
                        <name>cloudstack2</name>
                        <ipaddress>172.16.2.98</ipaddress>
                </property>
	</environment>
</configuration>


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 = "<html><body><table border=\"1\">\n"
	html_end = "</table></body></html>"
	html_str = html_start + "	<tr bgcolor=\"#ddee11\">\n"
        for i in tr_list:
                html_str = html_str + "         <td>%s</td>\n" % i
        html_str = html_str + " </tr>\n"
        for item in source_list:
                html_str += "   <tr>\n"
                for attr in tr_list:
			if attr not in item:
				html_str += "           <td></td>\n"
			else:
                        	html_str += "           <td>%s</td>\n" % item[attr]
                html_str += "   </tr>\n"
        return html_str+"</table></body></html><br>" 

if __name__ == '__main__':
	with open('/tmp/cs_info','a+') as f:
		f.truncate()
		for sate,vdcs in csBaseInfo().items():
			for item in vdcs:
				f.write('<h4>%s %s</h4>\n' % (sate,item['name']))
				cs = CloudstackInfo(sate,item['name'],item['ipaddress'])
				f.write(createHtml(cs.zone_attr_list,cs.getZoneJson()))
				f.write(createHtml(cs.host_attr_list,cs.getHostJson()))
				f.write(createHtml(cs.svm_attr_list,cs.getSvmJson()))


5、郵件發送


這裏整個代碼只是初步達到我要的結果,有很多可以改進的地方,也有更多的方式去實現。其實cloudstack有restapi可以調用,只是我不熟悉,只能自己寫一寫玩一玩,就當是練習吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章