Python利用Zabbix API定时报告存在报警的机器

由于手上的zabbix服务器有几个,有时会没注意报警短信,又懒得登陆上去看看zabbix,所以用Python利用zabbix的API获取有问题的机器每天早上发到我邮箱,foxmail又是我天天都用的东西,这样我就可以方便地看到所有有问题的机器了

zabbix_sendmail.py

#!/usr/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
#mail_to_list = ['lihuipeng@xxx.com',]
mail_host = 'smtp.163.com'
mail_user = 'testest'     #发件人邮箱帐号
mail_pass = '123456'      #发件人邮箱密码
mail_postfix = '163.com'
def send_mail(to_list,subject,content):
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = ";".join(to_list)
    #msg['to'] = to_list
                                                                                             
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False
                                                                                             
if __name__ == "__main__":
    print sys.argv[1]
    print sys.argv[2]
    print sys.argv[3]
    send_mail(sys.argv[1], sys.argv[2], sys.argv[3])

这个是我用来发邮件的脚本,原理就是连接到163邮箱发送邮件,这里我是注册了一个帐号专门用来发邮件的。

zabbix_report.py

#!/usr/bin/python
#coding:utf-8
import json
import urllib2
from urllib2 import URLError
import sys
import zabbix_sendmail
#接收人
mailtolist = ['test@163.com',]
#格式:zabbix地址,zabbix帐号,zabbix密码,邮件标题
zabbix_addresses=['http://test1.zabbix.com,admin,123456,test1','http://test2.zabbix.com,admin,123456,test2','http://test3.zabbix.com,admin,123456,test3']
class ZabbixTools:
    def __init__(self,address,username,password):
                                                                       
        self.address = address
        self.username = username
        self.password = password
                                                                       
        self.url = '%s/api_jsonrpc.php' % self.address
        self.header = {"Content-Type":"application/json"}
                                                                       
                                                                       
                                                                       
    def user_login(self):
        data = json.dumps({
                           "jsonrpc": "2.0",
                           "method": "user.login",
                           "params": {
                                      "user": self.username,
                                      "password": self.password
                                      },
                           "id": 0
                           })
                                                                       
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
                                                                   
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Auth Failed, please Check your name and password:", e.code
        else:
            response = json.loads(result.read())
            result.close()
            #print response['result']
            self.authID = response['result']
            return self.authID
                                                                           
    def trigger_get(self):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"trigger.get",
                           "params": {
                                      "output": [
                                                "triggerid",
                                                "description",
                                                "priority"
                                                ],
                                      "filter": {
                                                 "value": 1
                                                 },
                                      "expandData":"hostname",
                                      "sortfield": "priority",
                                      "sortorder": "DESC"
                                    },
                           "auth": self.user_login(),
                           "id":1              
        })
                                                                       
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
                                                                       
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            issues = response['result']
            content = ''
            if issues:
                for line in issues:
                    content = content + "%s:%s\r\n" % (line['host'],line['description'])
            return content
                                                                           
if __name__ == "__main__":
    for zabbix_addres in zabbix_addresses:
        address,username,password,subject = zabbix_addres.split(',')
        z = ZabbixTools(address=address, username=username, password=password)
        content = z.trigger_get()
        zabbix_sendmail.send_mail(mailtolist, subject, content)
    print "Done!"

这里就是利用API查询信息,然后通过上面的发邮件脚本把信息发出来,效果是这样的:

145315337.png

再添加一个crontab就OK~

本文出自 “运维笔记” 博客,请务必保留此出处http://lihuipeng.blog.51cto.com/3064864/1306261

ps:

可能有的人smtp发送会失败,说是认证没有通过,可以试试修改如下:

#!/opt/venv/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
mail_host = 'smtp.xxxxx.com'
mp = 'password'
mail_postfix = 'xxxxx.com'


def send_mail(to_list,subject,content):
 me = 'xxxxx@xxxxx.com'
 msg = MIMEText(content)
 msg['Subject'] = subject
 msg['From'] = me
 msg['to'] = ";".join(to_list)

 try:
 s = smtplib.SMTP(mail_host,25)
 s.ehlo()
 s.starttls()
 s.ehlo
 s.login(me,mp)
 s.sendmail(me,to_list,msg.as_string())
 s.close()
 return True
 except Exception,e:
 print str(e)
 return False

发表评论

电子邮件地址不会被公开。 必填项已用*标注