插件窝 干货文章 linux monit能监控哪些资源

linux monit能监控哪些资源

Monit 监控 check alert 813    来源:    2025-05-13

Monit 是一款功能强大的 Linux/Unix 开源监控工具,能够监控系统资源、服务、进程、文件等。以下是 Monit 能够监控的主要资源类型及具体说明:


1. 系统资源监控

  • CPU 使用率
    监控整体或单个进程的 CPU 占用(用户态、内核态、总使用率)。

    check system $HOST
    if cpu usage > 80% for 5 cycles then alert
    
  • 内存(Memory)
    监控物理内存和交换分区(Swap)的使用情况。

    check system $HOST
    if memory usage > 75% then alert
    
  • 负载(Load Average)
    监控系统 1/5/15 分钟的平均负载。

    check system $HOST
    if loadavg (1min) > 4 then alert
    
  • 磁盘空间
    监控分区或目录的磁盘使用量。

    check filesystem rootfs with path /
    if space usage > 80% then alert
    
  • 磁盘 I/O
    监控磁盘读写延迟或活动(需结合 iostat 或自定义脚本)。


2. 进程监控

  • 进程状态
    检查进程是否在运行、是否崩溃、是否占用过多资源。

    check process nginx with pidfile /var/run/nginx.pid
    if not exist then restart
    if cpu > 50% for 3 cycles then alert
    
  • 进程数量
    监控同类进程的数量(例如防止 fork bomb)。

    check process apache matching "httpd"
    if children > 100 then alert
    

3. 网络监控

  • 端口检测
    检查服务是否监听指定端口(TCP/UDP)。

    check host myservice with address 127.0.0.1
    if failed port 80 protocol http then alert
    
  • 网络协议
    支持 HTTP/HTTPS、SMTP、FTP 等协议的内容检测(如响应状态码、关键词)。

    check host example.com with address example.com
    if failed port 443 protocol https with timeout 10 seconds then alert
    
  • 网络接口
    监控网卡状态、带宽使用(需结合 ifconfig 或自定义脚本)。


4. 文件与目录监控

  • 文件属性
    检查文件大小、权限、时间戳、MD5/SHA1 校验和变化。

    check file myapp_conf with path /etc/myapp/config.conf
    if changed checksum then alert
    
  • 目录变化
    监控目录内文件的增删改(如日志目录暴增)。

    check directory /var/log with path /var/log
    if size > 1 GB then alert
    

5. 自定义脚本监控

  • 通过返回值
    执行自定义脚本或命令,根据退出状态码(0 为成功,非 0 为失败)触发动作。
    monit check program myscript with path "/usr/local/bin/check_service.sh" if status != 0 then alert

6. 时间同步监控(NTP)

  • 检查系统时间是否与 NTP 服务器同步。
    monit check host ntp with address ntp.example.com if failed port 123 type udp protocol ntp then alert

7. 邮件与通知

  • 支持邮件、Slack、自定义脚本等告警方式,配置在全局设置中:
    monit set mailserver smtp.example.com set alert admin@example.com

8. 主动恢复动作

Monit 不仅告警,还能自动修复问题,例如: - 重启崩溃的进程。 - 停止占用过多资源的进程。 - 清理临时文件。

示例:自动重启 Nginx

check process nginx with pidfile /var/run/nginx.pid
  start program = "/etc/init.d/nginx start"
  stop program = "/etc/init.d/nginx stop"
  if failed port 80 then restart

配置注意事项

  1. 配置文件路径:通常为 /etc/monitrc/etc/monit.d/
  2. 权限:需以 root 运行或赋予足够权限。
  3. 测试配置:执行 monit -t 检查语法。
  4. 日志:查看 /var/log/monit.log 调试问题。

总结

Monit 的监控能力覆盖了系统核心资源、服务可用性、文件完整性等场景,适合轻量级自动化监控和故障恢复。对于更复杂的分布式监控,可结合 Prometheus + Grafana 或 Zabbix 使用。