前言:
来到新公司,领导下发了个需求:每周需要对服务器进行一个巡检,以及分析ngxin趋势,由于公司实际生产环境服务器不是特别多,考虑暂时先用脚本完成该需求。
大致思路:收集数据 -> 写入excel制成图表 -> 发邮件
一、收集nginx数据
主要是对nginx log进行一个分析,统计数据。公司使用系统自带的logrotate切割nginx日志,只保存10天日志,并且压缩起来,使用shell分析出来会出现两个日期,遂:将日志文件拷贝到其他路径,解压,并逐个分析,脚本如下:
#!/bin/bash LogName=nginx.access.log* #日志文件名 LogPath=/var/log/nginx/nginx.access.log* #日志路径 NginxPath=/data/scripts/NginxLog/ #解压日志路径 Filename=/data/scripts/NginxLog/nginx.log #数据收集文件 Temporary=/data/scripts/NginxLog/temporary #一个临时文件 #拷贝文件并解压 `cp $LogPath $NginxPath` `gunzip $NginxPath$LogName` #由于日志有两个日期,比较蛋疼,下面输出结果为:13/May/2016 xxxx function Nglog() { for i in `awk ‘gsub(/\[/," ",$0)‘ $1|awk -F ":| " ‘{++S[$5]}END {for (i in S) print i}‘` do num=`grep "$i" $1|awk ‘{print $1}‘|sort|uniq -c |wc -l` echo $i $num done } #目录下所有日志进行分析 for i in `ls $NginxPath|grep nginx.access.log` do Nglog $NginxPath$i >> $Temporary done #去掉2016,输入到日志 ACC=`awk ‘{a[$1]+=$2}END{for(i in a)print i,a[i]}‘ $Temporary|sort|sed ‘s/\/[0-9]\{4\}//g‘` echo "$ACC" > $Filename #删除临时文件以及日志文件 rm -rf $Temporary rm -rf $NginxPath$LogName
这样就把日志收集起来,那么如何保存旧数据与新数据呢?
在根目录写另外一个脚本,每次执行前都把名字改成旧数据文件名
`mv $DataFile $LastData`
二、制成图表
使用xlsxwriter生成,部分代码如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import xlsxwriter import time import linecache DataFile=‘/data/scripts/ServerData‘ LastFile=‘/data/scripts/LastData‘ ###处理nginx日志 new_data = ngdata(DataFile) last_data = ngdata(LastFile) new_item=[] new_value=[] last_item=[] last_value=[] for i in new_data: new_item.append(i.split()[0]) new_value.append(int(i.split()[1])) for l in last_data: last_item.append(l.split()[0]) last_value.append(int(l.split()[1])) ###创建excel表格 Excel_name = "Server_%s.xlsx" % (time.strftime("%Y-%m-%d",time.localtime())) workbook = xlsxwriter.Workbook(Excel_name) worksheet = workbook.add_worksheet() ###项目的样式 ItemStyle = workbook.add_format({ ‘font_size‘:10, ‘bold‘:True, ‘bg_color‘:‘#101010‘, ‘font_color‘:‘#FEFEFE‘, ‘align‘:‘center‘, ‘align‘:‘vcenter‘, ‘top‘:2, ‘left‘:2, ‘right‘:2, ‘bottom‘:2 }) ###目标值的样式 ValueStyle = workbook.add_format({ ‘font_size‘:9, ‘font_color‘:‘#151515‘, ‘align‘:‘center‘, ‘align‘:‘vcenter‘, ‘top‘:2, ‘left‘:2, ‘right‘:2, ‘bottom‘:2 }) ###写入nginx 数据 row2 = 69 col2 = 0 col3 = 0 row3 = 74 col4 = 0 col5 = 0 worksheet.insert_textbox(‘D68‘,‘Nginx_New_Data‘,{‘fill‘:{‘none‘:True},‘width‘:150,‘height‘:35}) worksheet.insert_textbox(‘D73‘,‘Nginx_Last_Data‘,{‘fill‘:{‘none‘:True},‘width‘:150,‘height‘:35}) for nt in new_item: worksheet.write(row2,col2,nt,ItemStyle) col2 += 1 for nv in new_value: worksheet.write(row2+1,col3,nv,ValueStyle) col3 += 1 for lt in last_item: worksheet.write(row3,col4,lt,ItemStyle) col4 +=1 for lv in last_value: worksheet.write(row3+1,col5,lv,ValueStyle) col5 +=1 ###Nginx图表 NginxChart = workbook.add_chart({‘type‘:‘line‘}) #定义最新数据的线条颜色等 NginxChart.add_series({ ‘categories‘:‘=Sheet1!$A$70:$I$70‘, ‘values‘:‘=Sheet1!$A$71:$I$71‘, ‘data_labels‘:{‘value‘:True}, ‘name‘:‘New Data‘, ‘line‘:{ ‘color‘ : ‘#4A4AFF‘, ‘width‘:2, }, }) #定义旧数据线条颜色等 NginxChart.add_series({ ‘values‘:‘=Sheet1!$A$76:$I$76‘, ‘name‘:‘Last Data‘, ‘line‘:{ ‘color‘ : ‘#BEBEBE‘, ‘dash_type‘:‘dash_dot‘, ‘width‘:1, }, }) NginxChart.set_y_axis({‘name‘:‘Nginx‘}) worksheet.insert_chart(‘A78‘,NginxChart) workbook.close()
效果图:
三、发送邮件
生成excel后,发送邮件,部分代码如下:
import smtplib from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase sender = ‘邮箱地址‘ receiver = [‘发送人列表‘] subject = ‘Server Inspection(%s)‘ %(time.strftime("%Y.%m.%d",time.localtime())) smtpserver = ‘smtp.163.com‘ username = ‘用户名‘ password = ‘密码‘ msg = MIMEMultipart(‘alternative‘) msg[‘Subject‘] = subject html = """邮件正文 """ part = MIMEText(html,‘html‘,‘utf-8‘) #!这个地方要指定编码,不然发邮会出现乱码 msg.attach(part) att = MIMEText(open(Excel_name,‘rb‘).read(),‘base64‘,‘utf-8‘) att["Content-Type"] = ‘application/octet-stream‘ att["Content-Disposition"] = ‘attachment;filename=Server.xlsx‘ msg.attach(att) smtp = smtplib.SMTP() smtp.connect(‘smtp.163.com‘) smtp.login(username,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
最后
将脚本加入任务计划,定制时间执行。
附上最后包装效果:
本文出自 “猫妖的博客” 博客,请务必保留此出处http://maoyao.blog.51cto.com/8253780/1773074
python使用xlsxwriter模板完成nginx趋势图,并自动发邮件
原文地址:http://maoyao.blog.51cto.com/8253780/1773074