1、发送短信的python脚本:mail.py
# coding=utf-8
import sys
import smtplib
from email.mime.text import MIMEText
msg_from = 'xxxx@qq.com' # 发送方邮箱
passwd = 'xxxxxx' # 填入发送方邮箱的授权码
msg_to = 'xxx@qq.com' # 收件人邮箱
#subject = "zabbix监控" # 主题
#content = "zabbix服务不可用"# 正文
subject = sys.argv[1] #alert脚本中传入的$subject
content = sys.argv[2] #alert脚本中传入的$messages
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 邮件服务器及端口号
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
print
"发送成功"
except s.SMTPException :
print
"发送失败"
finally:
s.quit()
2、检测zabbix服务脚本:zabbix_alert.sh
#!/bin/bash
work_path=/opt/py_scripts #创建目录
echo "$(date "+%Y-%m-%d %H:%M:%S") is running " >> $work_path/mail.log #记录日志
date_string=`date +%F`
host_name=`hostname`
subject="${date_string}:zabbix服务异常"
message="自检zabbix服务未通过"
zabbix_server_listen_count=$(systemctl status zabbix-server.service|grep "Active: active"|wc -l)
if [[ 0 == $zabbix_server_listen_count ]]
then
python2 $work_path/mail.py $subject $message
fi
3、通过检测是否有最新日志,进行每日汇报,检测监控脚本是否正常执行。zabbix_alert_script_check.sh
#!/bin/bash
work_path=/opt/py_scripts
echo "$(date "+%Y-%m-%d %H:%M:%S") is running " >> $work_path/sh.log
date_string=`date +%F`
host_name=`hostname`
subject="${date_string}:zabbix-shell正常"
message="脚本正常运行"
zabbix_server_listen_count=$(tail -1 mail.log|awk -F ' ' '{print $1}'|grep $(date "+%Y-%m-%d")|wc -l)
if [[ 1 == $zabbix_server_listen_count ]]
then
python2 $work_path/mail.py $subject $message
fi
4、crontab -e 进行定时任务。
*/15 * * * * /bin/bash /opt/py_scripts/zabbix_alert.sh
30 8 * * * /bin/bash /opt/py_scripts/zabbix_alert_script_check.sh
5、成功发送