首页 > 代码库 > 运维自动化--cvs转换成xls,并且邮件发送给相关人员
运维自动化--cvs转换成xls,并且邮件发送给相关人员
线上通过执行脚本,生成cvs文件,但是相关人员希望能够以特定格式的xls统计给他们,根据cvs的方法名查找字典xls去对应相关的中文名称,并且添加一行进去。在这个背景下,写了这个自动化的脚本。crontab定期去执行这个脚本。
主要代码如下:
定义一个发送email的模块:
#!/usr/local/howbuy/virtualenv/bin/python #coding:utf-8 from email.mime.text import MIMEText import smtplib import sys default_encoding = ‘utf-8‘ if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) import os import logging import smtplib from email.mime.text import MIMEText import email.mime.multipart from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders #logpath=‘/data/logs/smslog/‘ #logname=os.path.basename(os.path.realpath(__file__)) #logger = logging.getLogger() #logging.basicConfig(filename =logpath+logname+‘.log‘,level = logging.INFO, format = ‘%(asctime)s - %(levelname)s: %(message)s‘) smtpserver = ‘c1.icoremail.net‘ username = ‘ops_notify@howbuy.com‘ password = ‘Howbuy.com_IT_sa_ops_2014‘ def send_mail(to_list,subject,content): msg=MIMEMultipart() msg=MIMEMultipart() me=‘root@zabbixserver.localhost‘ body = MIMEText(‘性能日志统计‘,‘plain‘,‘utf-8‘) msg.attach(body) msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1,utf-8" msg[‘Subject‘] = subject # msg[‘From‘] = me msg[‘From‘] = username msg[‘to‘] = to_list part = MIMEBase(‘application‘, ‘octet-stream‘) part.set_payload(open(content,‘r‘).read()) Encoders.encode_base64(part) part.add_header(‘Content-Disposition‘, ‘attachment‘,filename=‘performance.xls‘) msg.attach(part) try: # s = smtplib.SMTP(‘127.0.0.1‘) s = smtplib.SMTP(smtpserver) s.login(username,password) # s.sendmail(me,to_list,msg.as_string()) s.sendmail(username,to_list,msg.as_string()) s.close() print ‘success!‘ # logging.info(‘%s,%s,%s‘ %(to_list,subject,content)) return True except Exception,e: print str(e) # logging.error(‘[%s] %s,%s,%s‘ %(e,to_list,subject,content)) return False if __name__ == "__main__": send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
调用生成xls主程序:
#/usr/bin/env python #-*- coding: UTF-8 -*- import sys from pmail import * default_encoding = ‘utf-8‘ if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) import os import xlwt import xlrd import datetime import time eday=datetime.datetime.now().strftime("%Y%m%d") h=[‘任务‘,‘日期‘,‘调用方法‘,‘执行总次数‘,‘执行成功次数‘,‘执行异常次数‘,‘单次执行最小耗时(分)‘,‘单次执行最大耗时(分)‘,‘单次执行平均耗时(分)‘,‘执行总耗时(分)‘,‘业务数据笔数‘,‘业务数据处理速度(毫秒/笔)‘] class dd: def __init__(self,zdpath): self.data=http://www.mamicode.com/ xlrd.open_workbook(zdpath)"|") rowmethod=str(rowlist[1].strip()) for i in xrange(self.nrows): zd=self.table.row_values(i) zdmethod=str(zd[0].strip()) if rowmethod==zdmethod: name=str(zd[1].strip()) rowlist.insert(0,name) for ii in range(10): table.write(x,ii,rowlist[ii]) bbb=1 continue if not bbb: rowlist.insert(0,"") for ii in range(10): table.write(x,ii,rowlist[ii]) def sa(self): self.data.save(os.path.join(self.path,‘performance-‘+str(self.day)+‘.xls‘).decode(‘utf-8‘)) if __name__==‘__main__‘: os.popen(‘sh /data/app/fds-schedule-new/bin/performance/ScheduleTaskPerformanceAnalyzer.sh‘) os.popen(‘sh /data/logs/tomcat-console/batch/perfomance/BatchTaskPerformanceAnalyzer.sh‘) time.sleep(20) a=dd(r‘/data/logs/performance/zd.xlsx‘) epath=‘/data/logs/performance‘ a.task(r‘/data/logs/tomcat-console/batch/perfomance/BatchTaskPerformanceReport.csv‘,‘控台任务‘) a.task(r‘/data/app/fds-schedule-new/bin/performance/ScheduleTaskPerformanceReport.csv‘,‘定时任务‘) a.sa() time.sleep(40) p=‘性能日志统计-‘+str(eday) send_mail(‘752477168@qq.com‘,p,os.path.join(epath,‘performance-‘+str(eday)+‘.xls‘).decode(‘utf-8‘))#修改邮箱
字典模板:
cvs文件
xls:
本文出自 “12109115” 博客,请务必保留此出处http://12119115.blog.51cto.com/12109115/1857250
运维自动化--cvs转换成xls,并且邮件发送给相关人员
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。