233饿13 发表于 2015-12-18 09:14:04

利用Zabbix通过邮件发送Screen图形报表实现

最近,在练习python程序,心血来潮,想利用zabbix-API来实现Zabbix通过邮件发送Screen图形报表,以便预测故障的发生,直接上源码,本人菜鸟,程序有烂的地方,请各位高手原谅。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
import time
import shutil
import MySQLdb
import smtplib
import requests
import datetime
import urllib
import urllib2
import cookielib
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
# based on zabbix 2.4.4
zabbix_host = '127.0.0.1'
username = 'admin'
password = 'zabbix'
width = 400
height = 156
period = 86400
dbhost = 'localhost'
dbuser = 'zabbix'
dbpasswd = 'zabbix'
dbname = 'zabbix'
dbport = '3306'
GRAPH_PATH = '/tmp/zabbix_graph'
EMAIL_DOMAIN = 'iyunv.com'
EMAIL_USERNAME = 'kefu'
EMAIL_PASSWORD = 'p@ssw0rd'

recipients = ["/home/*.jpeg"]

graphid_list = []

def SQL_Exec(query):
    try:
      _Conn = MySQLdb.connect(host='localhost',user='zabbix',passwd='zabbix',port=3306,connect_timeout=20)
      _Conn.select_db(dbname)
      cur = _Conn.cursor()
      _Conn = cur.execute(query)
      if _Conn == 0:
            result = 0
      else:
            result = cur.fetchall()
      return result
      cur.close()
      _Conn.close()
    except MySQLdb.Error,e:
      print "mysql error:" ,e

def Save_Graph(zabbix_host,username,password,width,height,period):
    for c in SQL_Exec("select resourceid from screens_items where screenid='20'"):
      for d in c:
            graphid_list.append(int(d))
    for graphid in graphid_list:
      print graphid
      login_opt = urllib.urlencode({
      "name": username,
      "password": password,
      "autologin": 1,
      "enter": "Sign in"})
      get_graph_opt = urllib.urlencode({
      "graphid": graphid,
      "screenid": '16',
      "width": width,
      "height": height,
      "period": period})
      cj = cookielib.CookieJar()
      opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
      login_url = r"http://%s/index.php"%zabbix_host
      save_graph_url = r"http://%s/chart2.php"%zabbix_host
      opener.open(login_url,login_opt).read()
      data = opener.open(save_graph_url,get_graph_opt).read()
      filename = "%s.jpeg"%str(graphid)
      f = open(filename,"wb")
      f.write(data)
      f.close()
def send_mail(screen_name, graphs, to_list):
me = 'Zabbix <%s@%s>' % (EMAIL_USERNAME, EMAIL_DOMAIN)
def _create_msg():
    msg = MIMEMultipart('related')
    msg['Subject'] = 'Zabbix Screen Report: %s' % screen_name
    msg['From'] = me
    msg['To'] = ';'.join(to_list)
    msg.preamble = 'This is a multi-part message in MIME format.'
    contents = "<h1>Screen %s</h1><br>" % screen_name
    contents += "<table>"

    zbxText = MIMEText("""
<strong>内容</strong><br /><br />
<table border="0">
<tr>
<td>前3个图</td>
</tr>
<tr>
<td><img src="cid:image0"></td>
<td><img src="cid:image1"></td>
<td><img src="cid:image8"></td>
</tr>
<td>中间3个图</td>
</tr>
<tr>
<td><img src="cid:image2"></td>
<td><img src="cid:image3"></td>
<td><img src="cid:image7"></td>
</tr>
<td>最后3个图</td>
</tr>
<tr>
<td><img src="cid:image4"></td>
<td><img src="cid:image5"></td>
<td><img src="cid:image6"></td>
</tr>
</table>
    """,'html','utf-8')
    msg.attach(zbxText)

    for n in range(len(graphid_list)):
      zbx_img = open(r'%s.jpeg'%graphid_list, 'rb')
      msgImage = MIMEImage(zbx_img.read())
      zbx_img.close()
      msgImage.add_header('Content-ID', '<image%s>'%n)
      msg.attach(msgImage)
    msg_text = MIMEText(contents, 'html')
    msg_alternative = MIMEMultipart('alternative')
    msg_alternative.attach(msg_text)
    msg.attach(msg_alternative)
    return msg
try:
    server = smtplib.SMTP()
    server.connect('smtp.%s' % EMAIL_DOMAIN)
    server.login('%s@%s' % (EMAIL_USERNAME, EMAIL_DOMAIN), EMAIL_PASSWORD)
    server.sendmail(me, to_list, _create_msg().as_string())
    server.close()
    print 'send mail Ok!'
except Exception, e:
    print e
if __name__ == '__main__':
    import sys,re,os,smtplib
    from email.MIMEText import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email import Utils,Encoders
    Save_Graph(zabbix_host,username,password,width,height,period)
    send_mail(Save_Graph, recipients, ['kefu@iyunv.com'])




最后,获得如下图形









页: [1]
查看完整版本: 利用Zabbix通过邮件发送Screen图形报表实现