脚本巴巴 www.jiaoben88.com

脚本实现获取cloudstack中资源和一些状态信息以html报表显示

发布时间:2017-01-26 15:02:08编辑:脚本巴巴

本文主要为大家介绍下脚本实现获取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可以调用,只是我不熟悉,只能自己写一写玩一玩,就当是练习吧

上一篇:如何解决控件附件上传时超大附件无法上传的问题
下一篇:比较两个相同的对象方法代码

相关文章