#!/usr/bin/python
#-*-coding:utf-8 -*-
import sys
import datetime
import MySQLdb
import operator
import xlwt
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yester=today-oneday
yesterday=str(yester).replace("-", '')
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet('告警統計', cell_overwrite_ok=True)
HOST = 'localhost'
USER_NAME = "XXXX"
USER_PWD = "XXXX"
DB_NAME = 'zabbix_2'
regexp="故障PROBLEM"
db = MySQLdb.connect(HOST, USER_NAME, USER_PWD, DB_NAME,charset = 'utf8')
cursor = db.cursor()
sql = "select subject,count(*) from alerts where mediatypeid=4 and FROM_UNIXTIME(alerts.clock,'%%Y%%m%%d') regexp '%s' and subject regexp '%s' group by subject;" % (yesterday,regexp)
cursor.execute(sql)
l = cursor.fetchall()
sheet.write(0, 0, '服務器')
sheet.write(0, 1, '告警內容')
sheet.write(0, 2, '告警次數')
sheet.write(0, 3, '短信發送人')
i=0
while i < len(l):
sql1="select distinct users.alias from alerts join users on users.userid=alerts.userid where alerts.mediatypeid=4 and FROM_UNIXTIME(alerts.clock,'%%Y%%m%%d') regexp '%s' and alerts.subject='%s';" %(yesterday,l[i][0])
cursor.execute(sql1)
l2=cursor.fetchall()
print l2
sheet.write(i+1, 0, str(l[i][0]).replace('故障PROBLEM,服務器:','').replace('發生','').split(':',1)[0])
sheet.write(i+1, 1, str(l[i][0]).replace('故障PROBLEM,服務器:','').replace('發生','').split(':',1)[1])
sheet.write(i+1, 2, l[i][1])
sheet.write(i+1, 3, str(l2).replace('\'','').replace(',)',')').replace(')','').replace('(',''))
i=i+1
db.close()
book.save(r'/tmp/zabbix.xls')
效果如下: