基于zabbix-manager

python2.7

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: batistuta1977@163.com
# Date: 2018/5/23
import smtplib,datetime,os,sys,time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
date_rang=() # 保存查询性能数据的日期范围
def get_date_range():
    cur_date = datetime.datetime.now() # 获取今天的日期
    weekday = cur_date.weekday() # 获取当前星期几
    # print weekday
    # 获取查找星期一日期要减去的天数,0表示星期一
    Monday = cur_date - datetime.timedelta(days=weekday + 7) # 找出星期一的日期
    date_Mon = Monday.strftime("%Y-%m-%d") # 获取周一的日期
    Friday = Monday + datetime.timedelta(days=4) # 获取星期一加上四天,星期五
    date_Fri = Friday.strftime("%Y-%m-%d") # 获取星期五的日期
    # print date_Mon
    # print date_Fri
    return date_Mon,date_Fri
def send_mail():
    smtp_server = "mail.bluetek.com.cn"
    cur_date = datetime.datetime.now().strftime("%Y-%m-%d")
    # print cur_date
    subject = "weekly performance of servers report" + cur_date
    # print subject
    Sender = 'liudong@bluetek.com.cn'
    #to_receiver = ['mujj@bluetek.com.cn','wangym@bluetek.com.cn','zhangyh@bluetek.com.cn']
    #to_CC = ['menghl@bluetek.com.cn','liudong@bluetek.com.cn']
    to_receiver = ['liudong@bluetek.com.cn','wangym@bluetek.com.cn','zhangyh@bluetek.com.cn']
    to_CC = []
    Receiver = to_receiver + to_CC
    username = 'liudong@bluetek.com.cn'
    password = 'Zhrldalyx061010'
 
    #下面的to\cc\from最好写上,不然只在sendmail中,可以发送成功,但看不到发件人、收件人信息
    msgroot = MIMEMultipart('related')
    msgroot['Subject'] = subject
    msgroot['To'] = ','.join(to_receiver)
    msgroot['Cc'] = ','.join(to_CC)
    msgroot['from'] = Sender
    # MIMEText有三个参数,第一个对应文本内容,第二个对应文本的格式,第三个对应文本编码
    os.chdir('/usr/local/reports/') #Crontab的路径不正确,导致自动执行失败的测试
    thebody = MIMEText(subject,'plain','utf-8')
    msgroot.attach(thebody)
    xlsxpart = MIMEApplication(open('cpuusage.xls','rb').read())
    xlsxpart.add_header('Content-Disposition', 'attachment', filename='cpuusage.xls')
    msgroot.attach(xlsxpart)
    xlsxpart = MIMEApplication(open('Freemem.xls','rb').read())
    xlsxpart.add_header('Content-Disposition', 'attachment', filename='Freemem.xls')
    msgroot.attach(xlsxpart)
    xlsxpart = MIMEApplication(open('Freedisk.xls','rb').read())
    xlsxpart.add_header('Content-Disposition', 'attachment', filename='Freedisk.xls')
    msgroot.attach(xlsxpart)
    try:
        client = smtplib.SMTP()
        client.connect(smtp_server)
        client.login(username, password)
        client.sendmail(Sender, Receiver, msgroot.as_string())
        client.quit()
        print 'Report邮件发送成功!'
    except smtplib.SMTPRecipientsRefused:
        print 'Recipient refused'
    except smtplib.SMTPAuthenticationError:
        print 'Auth error'
    except smtplib.SMTPSenderRefused:
        print 'Sender refused'
    except smtplib.SMTPException, e:
        print e.message
def gen_report_files(date_range):
    Start_date = ' \"' + date_range[0]
    # print Start_date
    End_date = ' \"' + date_range[1]
    # print End_date
    cmd_cpu = 'nohup zabbix_api --report "CPU usage"' + Start_date + " 00:00:00\"" + \
         End_date + ' 24:59:00" --xls /usr/local/reports/cpuusage.xls > /dev/null'
    # print cmd_cpu
    os.popen(cmd_cpu)
    cmd_mem = 'nohup zabbix_api --report "Free Mem %"' + Start_date + " 00:00:00\"" + \
         End_date + ' 23:59:00" --xls /usr/local/reports/Freemem.xls > /dev/null'
    # print cmd_mem
    os.popen(cmd_mem)
    cmd_disk = 'nohup zabbix_api --report "Free disk space on"' + Start_date + " 00:00:00\"" + \
         End_date + ' 23:59:00" --xls /usr/local/reports/Freedisk.xls > /dev/null'
    # print cmd_disk
    os.popen(cmd_disk)
def rm_files():
    # time.sleep(60)
    os.popen('rm -fr *.xls')
if __name__ == '__main__':
    date_rang = get_date_range()
    # print date_range
    # print date_range[0]
    # print date_range[1]
    gen_report_files(date_rang)
    time.sleep(30)
    send_mail()
    rm_files()

月报脚本:

[root@NEVS-ZABBIX-P reports]# cat Monthly-report.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: batistuta1977@163.com
# Date: 5/28/18 import smtplib,datetime,os,sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header date_range=() def get_date_range():
last_month_date_first = datetime.datetime(datetime.date.today().year,datetime.date.today().month-1,1).strftime("%Y-%m-%d")
# print(last_month_date_first)
last_month_date_last = datetime.datetime(datetime.date.today().year,datetime.date.today().month,1) - datetime.timedelta(1)
last_month_date_last = last_month_date_last.strftime("%Y-%m-%d")
# print last_month_date_last
return last_month_date_first,last_month_date_last def gen_report_files(date_range):
Start_date = ' \"' + date_range[0]
# print Start_date
End_date = ' \"' + date_range[1]
# print End_date
cmd_cpu = 'nohup zabbix_api --report "CPU usage"' + Start_date + " 00:00:00\"" + \
End_date + ' 23:59:00" --xls /usr/local/reports/cpuusage_monthly.xls > /dev/null'
# print cmd_cpu
os.popen(cmd_cpu)
cmd_mem = 'nohup zabbix_api --report "Free Mem %"' + Start_date + " 00:00:00\"" + \
End_date + ' 23:59:00" --xls /usr/local/reports/Freemem_monthly.xls > /dev/null'
# print cmd_mem
os.popen(cmd_mem)
cmd_disk = 'nohup zabbix_api --report "Free disk space on"' + Start_date + " 00:00:00\"" + \
End_date + ' 23:59:00" --xls /usr/local/reports/Freedisk_monthly.xls > /dev/null'
print cmd_disk
os.popen(cmd_disk) cmd_icmp = 'nohup zabbix_api --report "ICMP loss"' + Start_date + " 00:00:00\"" + \
End_date + ' 23:59:00" --xls /usr/local/reports/ICMP_monthly.xls > /dev/null'
#print cmd_icmp
os.popen(cmd_icmp) def send_mail():
os.chdir('/usr/local/reports/')
smtp_server = "mail.bluetek.com.cn"
cur_date = datetime.datetime.now().strftime("%Y-%m-%d")
# print cur_date
subject = "Monthly performance of servers report " + cur_date
# print subject
Sender = 'liudong@bluetek.com.cn'
to_receiver = ['mujj@bluetek.com.cn','wangym@bluetek.com.cn','zhangyh@bluetek.com.cn']
to_CC = ['menghl@bluetek.com.cn','liudong@bluetek.com.cn']
Receiver = to_receiver + to_CC
username = 'liudong@bluetek.com.cn'
password = 'Zhrldalyx061010' #下面的to\cc\from最好写上,不然只在sendmail中,可以发送成功,但看不到发件人、收件人信息
msgroot = MIMEMultipart('related')
msgroot['Subject'] = subject
msgroot['To'] = ','.join(to_receiver)
msgroot['Cc'] = ','.join(to_CC)
msgroot['from'] = Sender thebody = MIMEText(subject,'plain','utf-8')
msgroot.attach(thebody) xlsxpart = MIMEApplication(open('cpuusage_monthly.xls','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='cpuusage_monthly.xls')
msgroot.attach(xlsxpart) xlsxpart = MIMEApplication(open('Freemem_monthly.xls','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='Freemem_monthly.xls')
msgroot.attach(xlsxpart) xlsxpart = MIMEApplication(open('Freedisk_monthly.xls','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='Freedisk_monthly.xls')
msgroot.attach(xlsxpart) xlsxpart = MIMEApplication(open('ICMP_monthly.xls','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='Freedisk_monthly.xls')
msgroot.attach(xlsxpart) try:
client = smtplib.SMTP()
client.connect(smtp_server)
client.login(username, password)
client.sendmail(Sender, Receiver, msgroot.as_string())
client.quit()
print 'Report邮件发送成功!'
except smtplib.SMTPRecipientsRefused:
print 'Recipient refused'
except smtplib.SMTPAuthenticationError:
print 'Auth error'
except smtplib.SMTPSenderRefused:
print 'Sender refused'
except smtplib.SMTPException, e:
print e.message if __name__ == '__main__':
date_range = get_date_range()
# print date_range
print 'begin generating reports in /root/reports...'
gen_report_files(date_range)
send_mail()

定时执行

[root@NEVS-ZABBIX-P reports]# crontab -l
0 2 * * 1 source ~/.bashrc && /usr/bin/python /usr/local/reports/auto_report.py
0 3 1 * * source ~/.bashrc && /usr/bin/python /usr/local/reports/Monthly-report.py

项目上使用的每月1日自动导出Zabbix性能数据的python脚本的更多相关文章

  1. Android系统下,用adb实现自动获取应用性能数据

    [自动化测试模式] 支持以adb shell命令的形式启动和运行.需要注意的是,office系列软件可能会更改命令中的字符,导致命令不可用!请手工输入命令,或从附带的command.txt文本中复制. ...

  2. 随手写的自动批量编译部署NativeAndroid程序Python脚本

    背景 有一堆工程NativeAndroid程序,要一一编译部署编译测试,手头只有AndroidManifest和Makefile,需要一个个Update,Ndk-build,和发包安装测试,很是头疼, ...

  3. Python脚本控制的WebDriver 常用操作 <二十六> 上传文件

    测试用例场景 上传文件的方法是找到上传文件的对象,通常是的对象.然后直接往这个对象send_keys,传入需要上传文件的正确路径.绝对路径和相对路径都可以,但是上传的文件必须存在,否则会报错. Pyt ...

  4. springboot项目上有个红叉,且ecplise没有自动编译项目,运行提示“错误: 找不到或无法加载主类”

    近期在做springboot项目,发现springboot项目上有个红叉但找不到哪个类报错,ecplise没有把项目自动编译,运行还提示“错误: 找不到或无法加载主类”,进入工作空间“项目\targe ...

  5. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  6. 有关项目上潜在需要的移动端GIS系统源码整理,待后续更新

    GPS Tools For Android 前言: GPS数据在做GIS开发时的一份宝贵的数据,在不侵犯他人隐私的情况下通过互联网的模式收集GPS是成本最为低廉的一种模式. 背景: 现在公司在做一个项 ...

  7. Gradle在大型Java项目上的应用

    在Java构建工具的世界里,先有了Ant,然后有了Maven.Maven的CoC[1].依赖管理以及项目构建规则重用性等特点,让Maven几乎成为Java构建工具的事实标准.然而,冗余的依赖管理配置. ...

  8. 在大型项目上,Python 是个烂语言吗

    Robert Love, Google Software Engineer and Manager on Web Search. Upvoted by Kah Seng Tay, I was the ...

  9. Git的使用-如何将本地项目上传到Github

    默认你的电脑上已经安装了git. 第一步:我们需要先创建一个本地的版本库(其实也就是一个文件夹). 你可以直接右击新建文件夹,也可以右击打开Git bash命令行窗口通过命令来创建. 现在我通过命令行 ...

随机推荐

  1. svn查看指定版本提交信息的命令

    通过svn命令查看指定版本提交的文件和日志信息 svn log -r ARG -v ARG :版本 可以是如下之一: NUMBER 版本号 '{' DATE '}' 在指定时间以后的版本 'HEAD' ...

  2. webServices学习二(小试牛刀。jdk 方式发布一个应用)

    一.前提 1.用Jdk1.6.0_21以后的版本发布一个WebService服务. 2.与Web服务相关的类,都位于javax.jws.*包中.  1.主要类有: 1.@WebService - 它是 ...

  3. Luogu P1712 [NOI2016]区间(线段树)

    P1712 [NOI2016]区间 题意 题目描述 在数轴上有 \(N\) 个闭区间 \([l_1,r_1],[l_2,r_2],...,[l_n,r_n]\) .现在要从中选出 \(M\) 个区间, ...

  4. 【python之路面向对象】初级篇

    概述 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发“更快更好更强...” 面向过程编程最易被初学 ...

  5. 做移动应用使用地图API时需要注意的问题

    最近在做一个基于地点提醒的移动应用,当初考虑大家都心知肚明的原因,谨慎的选择了百度地图,现在想想其实完全没有必要,好的应用本来就不分国界的,最后可能还是得换回Google地图.毕竟Google地图在技 ...

  6. 直接在安装了redis的Linux机器上操作redis数据存储类型--对key的操作

    一.概述:   前几篇博客中,主要讲述的是与Redis数据类型相关的命令,如String.List.Set.Hashes和Sorted-Set.这些命令都具有一个共同点,即所有的操作都是针对与Key关 ...

  7. angular4 Form表单相关

    ng4中,有两种方式去声明一个表单 一:Template-Driven Forms - 模板驱动式表单   [引入FormsModule] 1.ngForm赋值 [可以方便的获取表单的值] <f ...

  8. Mac下载Navicat premium提示文件损坏的解决方案

    首先打开终端,执行: sudo bash 这时会提示你输入你的账户密码, 输入完后就切换到了 root 用户,然后执行: xattr -cr /Applications/Navicat\ Premiu ...

  9. Vue.之.项目开发工具选用

    Vue.之.项目开发工具选用 上篇文章记录了创建项目,这篇文件记录,如何对创建的项目进行开发.这里选择一个工具:Visual Studio Code (请自行下载安装) 1. 打开VSCode工具,并 ...

  10. UE4物理模块(二)---建立物体碰撞

    在前文中介绍了什么是物理以及如何在UE4和PhysX中进行可视化调试: Jerry:UE4物理模块(一)---概述与可视化调试​zhuanlan.zhihu.com 这里调试只谈到了碰撞盒(后续还会有 ...