插件窝 干货文章 linux monit报警方式有哪些

linux monit报警方式有哪些

Monit 报警 Alert example 393    来源:    2025-05-13

Monit 是一款强大的 Linux 进程、文件、目录和系统资源监控工具,支持多种报警通知方式。以下是 Monit 的主要报警方式及配置方法:


1. 邮件报警(最常用)

通过 SMTP 发送邮件通知,需配置 Monit 的邮件服务参数:

# 在 /etc/monitrc 或 /etc/monit.d/mailserver 中配置
set mailserver smtp.example.com  # SMTP服务器地址
    port 587                     # 端口(可选)
    username "user@example.com"  # 认证用户名(可选)
    password "password"          # 认证密码(可选)
    using tlsv1                  # 加密方式(可选)

set mail-format {
    from: monit@example.com
    subject: "[Monit Alert] $EVENT: $SERVICE"
    message: "Host: $HOST\nEvent: $EVENT\nService: $SERVICE\nDate: $DATE\nAction: $ACTION\nDescription: $DESCRIPTION"
}

set alert admin@example.com  # 接收报警的邮箱

2. 自定义脚本报警

通过调用外部脚本(如 Shell/Python)发送通知,支持灵活集成(如短信、钉钉、Slack等):

# 在 monitrc 中配置
set alert sysadmin@example.com but exec "/path/to/alert_script.sh"

脚本示例 (alert_script.sh):

#!/bin/bash
# 接收Monit传递的环境变量
echo "Monit Alert: $MONIT_SERVICE - $MONIT_DESCRIPTION" | send_sms.py

3. HTTP/API 通知

通过 HTTP POST 请求将报警发送到 Webhook(如企业微信、Prometheus Alertmanager等):

check process nginx with pidfile /var/run/nginx.pid
    if failed port 80 then alert
    alert http://webhook.example.com/api/alert with {
        method="POST",
        header="Content-Type: application/json",
        content='{"service": "$SERVICE", "event": "$EVENT", "host": "$HOST"}'
    }

4. 本地日志记录

将报警写入本地日志文件(需配合 syslog 或日志工具分析):

set logfile /var/log/monit.log
set alert sysadmin@example.com not on { instance, action }

5. 条件过滤报警

通过 but not on 过滤特定事件避免冗余报警:

set alert admin@example.com but not on { pid, ppid }  # 忽略PID变化报警

6. 多接收人配置

支持为不同事件设置不同的接收人:

set alert dev-team@example.com on { timeout, resource }
set alert ops-team@example.com on { checksum, permission }

7. 集成第三方工具

  • Slack/Telegram:通过脚本调用其 API。
  • PagerDuty:使用 PagerDuty 的 Webhook 或邮件集成。
  • Zabbix/Nagios:通过 Monit 的 exec 触发 Zabbix/Nagios 的告警机制。

配置生效步骤

  1. 修改 /etc/monitrc/etc/monit/conf.d/ 下的配置文件。
  2. 检查语法:monit -t
  3. 重启 Monit 服务:systemctl restart monit

注意事项

  • 邮件报警需确保服务器能访问 SMTP 服务。
  • 脚本/HTTP 报警需确保脚本有执行权限或网络可达。
  • 使用 set daemon 60 控制检查频率(单位:秒)。

通过以上方式,Monit 可以灵活适配多种运维场景的报警需求。