CmdNotify - 命令监控技能
触发词
当用户提到以下关键词时激活此技能:
"监控命令"
"命令告警"
"定时执行脚本"
"输出变化检测"
"cmdnotify"
"command monitor"
"batch script execution"
使用场景
批量监控多个系统命令的输出变化
定时执行脚本并检测异常
磁盘使用率、内存、进程数等系统指标监控
API 健康检查与状态变化告警
配置文件漂移检测
日志模式监控
概述
CmdNotify 是一个用 Go 编写的轻量级、资源优化的命令监控系统。它允许您:
批量监控多个命令/脚本
为每个命令设置自定义执行间隔
自动检测输出变化(stdout/stderr + 退出代码)
当检测到变化时触发警报
使用 goroutine 池和超时机制以最小的 CPU/内存占用运行
快速开始
创建一个 config.json 文件:
{
"commands": [
{
"name": "disk_usage",
"command": "df -h /",
"interval": "30s",
"timeout": "10s",
"notify_on": ["change"],
"max_history": 2
},
{
"name": "memory_check",
"command": "vm_stat | grep 'Pages free'",
"interval": "20s",
"timeout": "5s",
"notify_on": ["change"],
"notify_cmd": "echo '[ALERT] $CMD_NAME: $CMD_MESSAGE'",
"max_history": 2
}
]
}
# 构建
go build -o cmdnotify .
# 运行默认配置
./cmdnotify
# 运行自定义配置
./cmdnotify -config /path/to/config.json
配置选项
字段 类型 默认值 描述
name string 必需 命令的唯一标识符
command string 必需 要执行的 Shell 命令
interval duration 1s 执行间隔(例如 30s、5m、1h)
timeout duration 30s 每次运行的最大执行时间
notify_on []string [] 要通知的事件:["change"]、["error"]、["all"]
notify_cmd string "" 自定义通知命令(可选)
max_history int 2 保留用于变化检测的结果数
working_dir string "" 命令执行的工作目录
通知默认行为
当未指定 notify_cmd 时,警报将打印到 stderr:
[disk_usage] 命令 'disk_usage' 输出已更改
退出代码:0
输出:
文件系统 大小 已用 可用 容量
/dev/disk1s1 228Gi 180Gi 48Gi 79%
自定义通知
设置 notify_cmd 以集成外部系统:
{
"notify_cmd": "curl -X POST -d '{\"text\":\"$CMD_MESSAGE\"}' https://hooks.slack.com/services/..."
}
notify_cmd 中可用的环境变量:
CMD_NAME - 命令名称
CMD_MESSAGE - 警报消息
资源优化
CmdNotify 设计为最小化资源消耗:
功能 实现
Goroutine 池 基于信号量的并发限制(默认:CPU 数,至少 4)
超时控制 每个命令的 context.WithTimeout 防止僵死进程
内存复用 bytes.Buffer 用于输出;历史记录限制为 max_history
高效哈希 输出 + 退出代码的 SHA-256 快速变化检测
优雅关闭 context.Cancel + sync.WaitGroup 确保干净退出
项目结构
CmdNotify/
├── config.go # 配置加载和验证
├── config.json # 示例配置
├── executor.go # 命令执行和变化检测
├── scheduler.go # 调度引擎,具有 Goroutine 池
├── main.go # 入口点
└── go.mod # Go 模块定义
使用场景
监控磁盘使用变化
跟踪进程数量
监控日志文件模式
检查服务健康端点
检测配置漂移
监控系统资源使用
高级示例
{
"commands": [
{
"name": "api_health",
"command": "curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/health",
"interval": "10s",
"timeout": "5s",
"notify_on": ["change", "error"],
"notify_cmd": "echo '[$(date)] $CMD_NAME 状态更改:$CMD_MESSAGE' >> /var/log/alerts.log",
"max_history": 3
},
{
"name": "db_connection_count",
"command": "psql -c 'SELECT count(*) FROM pg_stat_activity;' -t",
"interval": "1m",
"timeout": "10s",
"notify_on": ["all"],
"working_dir": "/opt/monitoring"
}
]
}