You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Monit邮件格式中使用主机名以外的标识识别主机?

可行解决思路

1. 全局宏变量结合预生成标识脚本

  • 编写系统脚本(如/usr/local/bin/get_host_id.sh),输出包含IP、虚拟机ID等组合的唯一标识,示例脚本内容:
    #!/bin/bash
    IP=$(hostname -I | awk '{print $1}')
    VM_ID=$(dmidecode -s system-serial-number | head -n1)
    echo "$IP-training-vm-$VM_ID"
    
  • 在Monit全局配置段(/etc/monit/monitrc)中,定时执行脚本并将结果写入临时文件,同时定义全局宏:
    exec "/usr/local/bin/get_host_id.sh > /tmp/monit_host_tag" every 1 cycles
    set macro.host_tag `/bin/cat /tmp/monit_host_tag`
    
  • 在mail-format中直接调用$host_tag变量,示例:
    set mail-format {
        subject: ALERT - $host_tag - $SERVICE failed
        message: Host Identity: $host_tag\n$DESCRIPTION
    }
    

2. 修改Monit源码扩展内置变量(适合有编译能力的场景)

  • 下载Monit源码,修改src/monit.h或src/util/System.c,添加新的内置变量(如$ipaddress),让Monit启动时自动获取主机主IP
  • 重新编译安装Monit,之后直接在mail-format中使用$ipaddress,无需额外配置

3. 本地邮件转发脚本二次处理告警

  • 配置Monit将告警邮件发送到本地邮件服务的专用邮箱(如monit-alert@localhost)
  • 编写Shell/Python脚本监听该邮箱,读取邮件内容后追加IP等标识,再转发给目标收件人,示例Shell脚本逻辑:
    #!/bin/bash
    CONTENT=$(cat)
    IP=$(hostname -I | awk '{print $1}')
    NEW_CONTENT="Host IP: $IP\n\n$CONTENT"
    echo -e "$NEW_CONTENT" | sendmail your-alert@example.com
    
  • 在本地邮件服务中配置规则,将发送到monit-alert@localhost的邮件转发给该脚本处理

4. 批量生成带标识的检查配置

  • 若仍需使用check program,编写配置生成脚本,批量为所有检查添加标识信息:
    • 先导出现有Monit检查配置到模板文件
    • 用脚本遍历模板,自动插入包含IP标识的mail-format片段
    • 示例生成的检查配置:
      check program check_apache with path "/usr/local/bin/check_apache.sh"
          if status != 0 then alert
          mail-format {
              subject: ALERT - $HOST ($(hostname -I)) - apache failed
              message: Host IP: $(hostname -I)\n$DESCRIPTION
          }
      

内容的提问来源于stack exchange,提问作者Rob_L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:05:01