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

本文主要是介绍脚本实现获取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 jsondef 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 Nonedef 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 outpathdef 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 pythonimport os,sys
import logging
sys.path.append("/home/test/cbin/script/lib/")
import json
import sshLiblogging.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"+infoclass CloudstackInfo(Base):def __init__(self,satellite,name,ip):self.satellite = satelliteself.name = nameself.ip = ipself.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 infodef 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 CloudstackInfodef 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').textprp_dic['ipaddress'] = prp.find('ipaddress').textprp_list.append(prp_dic)evi_dic[evi.attrib['satellite']] = prp_listreturn evi_dicdef 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" % ihtml_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可以调用,只是我不熟悉,只能自己写一写玩一玩,就当是练习吧

这篇关于脚本实现获取cloudstack中资源和一些状态信息以html报表显示的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1015073

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

Python获取浏览器Cookies的四种方式小结

《Python获取浏览器Cookies的四种方式小结》在进行Web应用程序测试和开发时,获取浏览器Cookies是一项重要任务,本文我们介绍四种用Python获取浏览器Cookies的方式,具有一定的... 目录什么是 Cookie?1.使用Selenium库获取浏览器Cookies2.使用浏览器开发者工具