首页 > 代码库 > python练习

python练习

python去zabbix的mysql数据库中取交换机不同时间段的进出口流量,然后写入excel中,每天cron执行,下周一邮件发送。(代码中第一行必须加上,不然crontab执行不了,或者在crontab时指明环境变量)

技术分享
#!/usr/local/bin/python2.7#_*_coding:utf-8_*_import MySQLdbimport timefrom datetime import datetimefrom datetime import timedeltafrom openpyxl import Workbookfrom openpyxl import load_workbook#根据系统时间选不同时间段now = datetime.now()now2 = now.strftime(%H:%M)if now2 == 19:00:    a = timedelta(hours=-10.5)    Column = 2elif now2 == 23:59:    a = timedelta(hours=-5)    Column = 8else:    a = timedelta(hours=-8.5)    Column = 14Column1 = Columnbefore = now + a[root@bj01-ops-zbx01 ~]# vim monitor.py #!/usr/local/bin/python2.7#_*_coding:utf-8_*_import MySQLdbimport timefrom datetime import datetimefrom datetime import timedeltafrom openpyxl import Workbookfrom openpyxl import load_workbooknow2 = now.strftime(%H:%M)if now2 == 19:00:    a = timedelta(hours=-10.5)    Column = 2elif now2 == 23:59:    a = timedelta(hours=-5)    Column = 8else:    a = timedelta(hours=-8.5)    Column = 14Column1 = Columnbefore = now + anow = 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 dataIn = get_data(212535)Out = get_data(212583)tunple = In + Out#输出结果合并一个元组中#写入excelwb = load_workbook("2.xlsx")#打开excelws = 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        breakfor k,v in enumerate(tunple):  pass  if Column1 < Column+6:    ws.cell(row=Row, column=Column1).value =http://www.mamicode.com/ tunple[k]    Column1 += 1wb.save(2.xlsx)
View Code

 

python练习