FXMAR 发表于 2018-12-29 14:23:05

keepalived 发送告警邮件到外部邮箱

  邮件脚本:
  keepalived_notify.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import sys, time, subprocess, random

# 第三方 SMTP 服务
mail_host="smtp.exmail.qq.com"#设置服务器
# 设置发送邮件的用户及密码,可设置多个
userinfo_list = [{'user':'user1@qq.com','pass':'user1_pass'}, {'user':'user2@qq.com','pass':'user2_pass'}, {'user':'user3@qq.com','pass':'user3_pass'}]
user_inst = userinfo_list
mail_user=user_inst['user']    #用户名
mail_pass=user_inst['pass']   #口令

sender = 'pairobot2@tuandai.com'    # 邮件发送者
receivers = ['xx1@qq.com', 'xx2@163.com']# 接收邮件,可设置为你的QQ邮箱或者其他邮箱
p = subprocess.Popen('hostname', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
hostname = p.stdout.readline().split('\n')
message_to = ''
for i in receivers:
    message_to += i + ';'
def print_help():
    note = '''python script.py role ip vip
    '''
    print(note)
    exit(1)
time_stamp = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
if len(sys.argv) != 4:
    print_help()
elif sys.argv == 'master':
    message_content = '%s server: %s(%s) change to Master, vIP: %s' %(time_stamp, sys.argv, hostname, sys.argv)
    subject = '%s change to Master -- keepalived notify' %(sys.argv)
elif sys.argv == 'backup':
    message_content = '%s server: %s(%s) change to Backup, vIP: %s' %(time_stamp, sys.argv, hostname, sys.argv)
    subject = '%s change to Backup -- keepalived notify' %(sys.argv)
else:
    print_help()
message = MIMEText(message_content, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] =Header(message_to, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件")
    print(e)  使用方法:

python script.py{脚本名} role{master|backup} ip{本keepalived服务器IP} vip{虚拟IP}  

  master keepalived:
global_defs {
      notification_email {
                xx@qq.com
      }
      notification_email_from keepalived@qq.com
      smtp_server 127.0.0.1
      smtp_connect_timeout 30
      router_id LVS_DEVEL
}
## 上面的配置邮件只能发送到本机,mail 可查看

vrrp_script chk_http_port {
      script "

猫小乐 发表于 2018-12-29 15:58:08

good
页: [1]
查看完整版本: keepalived 发送告警邮件到外部邮箱