标签:
python去zabbix的mysql数据库中取交换机不同时间段的进出口流量,然后写入excel中,每天cron执行,下周一邮件发送。(代码中第一行必须加上,不然crontab执行不了,或者在crontab时指明环境变量)
#!/usr/local/bin/python2.7 #_*_coding:utf-8_*_ import MySQLdb import time from datetime import datetime from datetime import timedelta from openpyxl import Workbook from openpyxl import load_workbook #根据系统时间选不同时间段 now = datetime.now() now2 = now.strftime(‘%H:%M‘) if now2 == ‘19:00‘: a = timedelta(hours=-10.5) Column = 2 elif now2 == ‘23:59‘: a = timedelta(hours=-5) Column = 8 else: a = timedelta(hours=-8.5) Column = 14 Column1 = Column before = now + a [root@bj01-ops-zbx01 ~]# vim monitor.py #!/usr/local/bin/python2.7 #_*_coding:utf-8_*_ import MySQLdb import time from datetime import datetime from datetime import timedelta from openpyxl import Workbook from openpyxl import load_workbook now2 = now.strftime(‘%H:%M‘) if now2 == ‘19:00‘: a = timedelta(hours=-10.5) Column = 2 elif now2 == ‘23:59‘: a = timedelta(hours=-5) Column = 8 else: a = timedelta(hours=-8.5) Column = 14 Column1 = Column before = now + a now = now.strftime(‘%Y-%m-%d %H:%M‘) before = before.strftime(‘%Y-%m-%d %H:%M‘) #去mysql中取数据 def get_data(id): conn = MySQLdb.connect(host=‘10.125.2.31‘,user=‘zabbix‘,passwd=‘zabbix‘,db=‘zabbix‘) cur = conn.cursor() params = (id,before,now) reCount = cur.execute(sql,params) data = cur.fetchone() cur.close() conn.close() return data In = get_data(‘212535‘) Out = get_data(‘212583‘) tunple = In + Out#输出结果合并一个元组中 #写入excel wb = load_workbook("2.xlsx")#打开excel ws = wb.get_sheet_by_name(‘IDC‘)#打开sheet‘IDC流量’ #取出第一列中每一行的数据,判断写入位置 b = [] for row_list in range(6,11): a = ws.cell(row = row_list,column = Column).value row_list += 1 b.append(a) #判断第一列每一行是否为空,为空就退出for循环 for i in range(5): if not b[i]: Row = 6+i break for k,v in enumerate(tunple): pass if Column1 < Column+6: ws.cell(row=Row, column=Column1).value = tunple[k] Column1 += 1 wb.save(‘2.xlsx‘)
标签:
原文地址:http://www.cnblogs.com/hongpeng/p/5874901.html