zabbix_sendmail.py

本文介绍了一个使用Python编写的脚本,用于通过SMTP服务器发送Zabbix系统的告警邮件通知。该脚本配置了163邮箱作为邮件发送方,并支持自定义收件人地址、邮件主题及内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/python
#coding:utf-8

import smtplib
from email.mime.text import MIMEText
import os
import argparse
import logging
import datetime
 
mail_host = ' smtp.163.com'
mail_user = 'monitor_itnihao'
mail_pass = '123456'
mail_postfix = ' 163.com'
 
#mail_host=' smtp.qq.com'
#mail_user='itnihao'
#mail_pass='123456'
#mail_postfix=' qq.com'
 
def send_mail(mail_to,subject,content):
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = mail_to
    global sendstatus
    global senderr
     
    try:
        smtp = smtplib.SMTP()
        smtp.connect(mail_host)
        smtp.login(mail_user,mail_pass)
        smtp.sendmail(me,mail_to,msg.as_string())
        smtp.close()
        print 'send ok'
        sendstatus = True
    except Exception,e:
        senderr=str(e)
        print senderr
        sendstatus = False
     
def logwrite(sendstatus,mail_to,content):
    logpath='/var/log/zabbix/alert'
 
    if not sendstatus:
        content = senderr
 
    if not os.path.isdir(logpath):
        os.makedirs(logpath)
 
    t=datetime.datetime.now()
    daytime=t.strftime('%Y-%m-%d')
    daylogfile=logpath+'/'+str(daytime)+'.log'
    logging.basicConfig(filename=daylogfile,level=logging.DEBUG)
    os.system('chown zabbix.zabbix {0}'.format(daylogfile))
    logging.info('*'*130)
    logging.debug(str(t)+' mail send to {0},content is :\n {1}'.format(mail_to,content))
 
 
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Send mail to user for zabbix alerting')
    parser.add_argument('mail_to',action="store", help='The address of the E-mail that send to user ')
    parser.add_argument('subject',action="store", help='The subject of the E-mail')
    parser.add_argument('content',action="store", help='The content of the E-mail')
    args = parser.parse_args()
    mail_to=args.mail_to
    subject=args.subject
    content=args.content
 
    send_mail(mail_to,subject,content)
    logwrite(sendstatus,mail_to,content)
### 编写 Zabbix 与阿里云集成的 Shell 脚本 为了实现 Zabbix 和阿里云之间的集成,可以创建一个名为 `zabbix_aliyun.sh` 的 shell 脚本来处理这一过程。该脚本将负责调用阿里云 API 来获取所需数据并将其发送到 Zabbix 服务器。 #### 创建 zabbix_aliyun.sh 文件结构 首先定义文件的基础框架: ```bash #!/bin/bash # 配置参数 ALICLOUD_ACCESS_KEY="your_access_key" ALICLOUD_SECRET_KEY="your_secret_key" ZABBIX_SERVER="http://your_zabbix_server/zabbix" HOST_NAME="hostname" # 安装依赖工具 if ! command -v aliyun &> /dev/null; then echo "Aliyun CLI not found, installing..." curl https://mirrors.aliyun.com/acs-cli/install.sh | bash fi # 获取实例状态信息 get_instance_status() { local instance_id=$1 response=$(aliyun ecs DescribeInstances --RegionId cn-hangzhou --InstanceId $instance_id) status=$(echo "$response" | grep InstanceStatus | awk -F'"' '{print $4}') echo $status } # 发送数据至 Zabbix Server send_to_zabbix() { key=$1 value=$2 zabbix_sender -k "${key}" -o "${value}" } ``` 此部分设置了必要的配置变量以及安装了 Aliyun CLI 工具来简化后续操作[^1]。函数 `get_instance_status()` 可以用来查询特定 ECS 实例的状态;而 `send_to_zabbix()` 函数则实现了向指定主机名的目标键发送值给 Zabbix server 功能[^2]。 #### 添加主要逻辑流程控制 接下来,在上述基础上增加主程序逻辑: ```bash main(){ INSTANCE_ID="i-bp1a90y7h****jgq5****" # 替换成自己的ECS ID while true; do STATUS=$(get_instance_status ${INSTANCE_ID}) send_to_zabbix "ecs.status" "${STATUS}" sleep 60 # 每隔一分钟执行一次检测 done } main ``` 这段代码通过无限循环不断轮询 ECS 实例的状态,并每隔六十秒更新一次最新状态给定于 Zabbix 中对应的监控项上。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值