环境:MySQLdb openpyxl模块

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 = 8
elif now2 == '23:59':
  a = timedelta(hours=-5)
  Column = 14
else:
  a = timedelta(hours=-8.5)
  Column = 2
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()

  sql = "select min(round(value/1000/1000,2)) as MIN,avg(round(value/1000/1000,2)) as AVG,max(round(value/1000/1000,2)) as MAX from history where itemid=%s and from_unixtime(clock)>%s and from_unixtime(clock)<%s  "
  params = (id,before,now) 
  reCount = cur.execute(sql,params)
  data = cur.fetchone()

  cur.close()
  conn.close()
  return data



#写入excel
wb = load_workbook("/home/hongpeng/network/network_flow.xlsx")#打开excel
ws = wb.get_sheet_by_name('IDC')#打开sheet‘IDC流量’
def write(begin,over,Column1 = Column):
  #取出第一列中每一行的数据,判断写入位置
  b = []
  for row_list in range(begin,over+1):
    a = ws.cell(row = row_list,column = Column).value
    row_list += 1
    b.append(a)
  #判断第一列每一行是否为空,为空就退出for循环,找到插入位置
  for i in range(len(b)):
    if not b[i]:
      Row = begin+i
      break
  for k,v in enumerate(tunple):
    pass
    if Column1 < Column+8:
      ws.cell(row=Row, column=Column1).value = tunple[k]
      Column1 += 1
  wb.save('/home/hongpeng/network/network_flow.xlsx')
    
if __name__ == '__main__':
  In = get_data('212535')
  Out = get_data('212583')
  tunple = In + Out
  write(6,12)
  In1 = get_data('231087')
  Out1 = get_data('231671')
  tunple = In1+Out1
  write(18,24)
View Code

相关文章:

  • 2021-07-05
  • 2021-11-30
  • 2022-02-09
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-30
  • 2022-02-08
  • 2022-12-23
相关资源
相似解决方案