zabbix アラートスクリプト

サンプルコード:

ファイル名:alertsend.sh

#!/usr/bin/python
# -*- coding: utf8 -*-
#zabbix remote command
import time,datetime
import re,os
import sys
import zabbix_sendmail
from zabbix_sendmail import SendmailError
import subprocess
import logging
from logging.handlers import RotatingFileHandler
reload(sys)
sys.setdefaultencoding('utf-8’)
LOGFILE = “/apps/svr/zabbix_server/scripts/logs/out.log"
MAXLOGSIZE = 100*1024*1024
BACKUPCOUNT = 4
log = logging.getLogger('zabbix_exec_command’)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s – %(levelname)s: %(message)s’)
fh = RotatingFileHandler(LOGFILE,maxBytes=MAXLOGSIZE,backupCount=BACKUPCOUNT)
ch = logging.StreamHandler()
fh.setFormatter(formatter)
ch.setFormatter(formatter)
log.addHandler(fh)
log.addHandler(ch)
def get_2hour_ago():
a = os.popen(“date +%Y%m%d%H -d '2 hours ago'").readlines()[0]
b = a.strip()
return b
def run_command(ip,command):
cmd = “zabbix_get -s " + ip + " -k 'system.run[\"" + command + “\"]'"
return os.popen(cmd).readlines()
mailcontent = “"
if __name__ == “__main__":
to_list = []
to_mobile = []
if len(sys.argv) != 8:
print “show usage: %s serverip itemid itemname hostname itemkey itemvalue triggerstatus" % (sys.argv[0])
sys.exit(1)
mailcontent = “""
<html>
<body>
<meta http-equiv="Content-Type" content="text/html";charset=utf-8>
<title>ビッグデータモニタリングメール</title>
<style type="text/css">
.body { font-size: 14px; color: #333;background-color: #fff;}
.divtd {color:#E28E40;}
</style>
“""
ip,itemid,itemname,hostname = sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4]
itemkey,itemvalue,triggerstatus = str(sys.argv[5]).replace(" “,""),str(sys.argv[6]).replace(" “,""),sys.argv[7]
log.info(“アラート:IP:%s,監視項目:%s,ホスト名:%s,監視key:%s"%(ip,itemname,hostname,itemkey))
time_start = get_2hour_ago()
mailcontent += “<div class=’divtd’> 監視項目:%s , ホスト名:%s ,IP:%s ,現在値: %s </div><br />" % (itemname,hostname,ip,itemvalue)
mailcontent += “<div class=’divtd’>メモリ:</div> <div class=’.body’>"
for line in run_command(ip,"free -m"):
line=line.strip()
mailcontent += “%s<br />" % line
mailcontent += “<br /></div>"
mailcontent += “<div class=’divtd’>IO情報:</div> <div class=’.body’>"
for line in run_command(ip,"iostat -xn 1 1″):
line=line.strip()
mailcontent += “%s<br />" % line
mailcontent += “<br /></div>"
mailcontent += “<div class=’divtd’>負荷情報:</div> <div class=’.body’>"
for line in run_command(ip,"sar -q 1 3″):
line=line.strip()
mailcontent += “%s<br />" % line
mailcontent += “<br /></div>"
mailcontent += “<div class=’divtd’>CPU情報:</div> <div class=’.body’>"
for line in run_command(ip,"mpstat -P ALL"):
line=line.strip()
mailcontent += “%s<br />" % line
mailcontent += “<br /></div>"
mailcontent += “<div class=’divtd’>システムログ:</div> <div class=’.body’>"
for line in run_command(ip,"/usr/bin/sudo tail -20 /var/log/messages"):
line=line.strip()
mailcontent += “%s<br />" % line
mailcontent += “<br /></div>"
to_list = [“xxxx"]
mailcontent += “<div class=’divtd’>履歴データ:</div> <div class=’.body’>"
mailcontent += “<table style=’border-collapse: collapse; width: 96%;’>"
mailcontent += “""<tr><img src=http://xxxxxx/chart.php?itemid=%s&period=7200&stime=%s width="871″ height="305″/>""" % (itemid,time_start)
mailcontent += “</tr> </table>"
mailcontent += “""</html>
</body>"""
print mailcontent
log.debug(“監視メール内容:%s"%mailcontent)
log.info(“受信:%s,受信者リスト:%s"%(to_list,to_mobile))
mail_sub = “Zabbix監視アラーム|現在状態:%s,監視項目:%s,監視ホスト:%s " % (triggerstatus,itemname,hostname)
log.info(“メールを送信,件名:%s"%mail_sub)
try:
zabbix_sendmail.send_mail_withoutSSL(to_list,mail_sub,mailcontent)
log.info(“アラームメール送信成功")
except SendmailError,e:
log.error(“アラーム送信失敗,失敗メッセージ:%s"%(str(e)))

2.sendmailの中身下記

#!/usr/bin/python
# -*- coding: utf8 -*-
#to send zabbix alert mail
import smtplib
from email.mime.text import MIMEText
import traceback
import exceptions
import sys
reload(sys)
sys.setdefaultencoding('utf-8′)
mail_host = “xxxxx"
mail_user = “xxxx"
mail_pass = “xxxx"
mail_address = “xxx"
mail_postfix="xxxx"
mail_port="xxx"
class SendmailError(Exception):
def __init__(self, errorlog):
self.errorlog = errorlog
def __str__(self):
return “メール送信エラー,エラーメッセージ: %s" % (self.errorlog)
def send_mail_withoutSSL(to_list,sub,content):
me = “BI Monitor" + “<“+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,’html’,’utf8′)
msg['Subject’] = sub
msg['From’] = me
msg['To’] = “;".join(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:
raise SendmailError(str(e))

 

Source

Posted by arkgame