脚本实现获取cloudstack中资源和一些状态信息以html报表显示
2017-04-01 16:57
399 查看
环境中有多个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
5、邮件发送
这里整个代码只是初步达到我要的结果,有很多可以改进的地方,也有更多的方式去实现。其实cloudstack有restapi可以调用,只是我不熟悉,只能自己写一写玩一玩,就当是练习吧
下面是一个简化版的思路:
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可以调用,只是我不熟悉,只能自己写一写玩一玩,就当是练习吧
相关文章推荐
- 脚本实现获取cloudstack中资源和一些状态信息以html报表显示
- 用vbs实现获取电脑硬件信息的脚本_最新版第1/4页
- 使用android-rss库实现从网络中获取rss信息,并通过ListView显示
- Linux 下实现控制屏幕显示信息和光标的状态
- JavaScript + jQuery + HTML 实现<input>提示信息的显示、隐藏,功能与jQuery EasyUI的easyui-textbox的prompt属性相同。
- jQuery Ajax 实现在html页面实时显示用户登录状态
- 通过读proc等方式获取Linux系统状态信息的一些方法
- 使用QTextEdit实现状态信息显示框
- Python获取电脑硬件信息及状态的实现方法
- Python获取电脑硬件信息及状态的实现方法
- Android中 获取手机信息以及联网状态的一些工具类小结
- 巧用锐浪报表:用报表脚本实现动态显示小数位数
- 简单脚本之显示系统当前的一些信息
- 使用linux的shell脚本实现在当前行重复动态显示时间等字符串信息(不另起新行)
- 从服务器获取报表模板到html页面显示报表pdf
- 状态栏显示欢迎信息的脚本特效
- aspnetpager 获取或设置在显示在用户自定义信息区的用户自定义HTML文本内容。
- Ruby: 获取IE的一些信息(其实应用AutoIt脚本本身,获取这些信息更加简单)
- Jquery load实现用户在html页面实时显示登录状态
- 利用脚本获取mysql的tps,qps等状态信息