如何调用 nagios-api 创建联系人并设置微信通知?
解读
国内面试官问这道题,不是让你背 curl 命令,而是考察三件事:
- 是否知道 Nagios 自身没有官方 RESTful API,必须借助社区版 nagios-api 或自写 CGI 封装;
- 能否把“写配置”与“发微信”两条链路串起来——配置层(联系人对象)+ 告警层(通知命令)+ 通道层(企业微信/微信机器人);
- 是否具备灰度验证与回滚意识,避免直接改 production 配置导致告警雪崩。
如果候选人一上来就答“调 POST /contacts” 直接 200,直接扣分——Nagios 的联系人本质是文本片段,任何 API 都只是帮你写文件并 reload。
知识点
-
nagios-api 安装与鉴权
- 国内源:清华镜像拉取 rpmforge,pip install nagios-api 后生成 systemd 服务;
- 鉴权:使用 htdigest 创建 nagios 用户,面试时要强调“绝不明文写密码在脚本里”,而是走环境变量或 vault。
-
联系人对象最小字段
contact_name、alias、email、pager(国内习惯把微信 hook 地址写在这里)、service_notification_commands、host_notification_commands。 -
微信通知命令写法
企业微信最稳:/usr/local/nagios/libexec/notify_wechat.py
关键参数:CORP_ID、AGENT_ID、SECRET 通过 /etc/nagios/private/wechat.env 读取,避免硬编码。 -
重载流程
nagios-api 的 POST /config/contact 只是写 objects/contacts/api_contacts.cfg,必须调用 /reload 端点;
生产环境要 pre-flight check:/usr/local/nagios/bin/nagios -v /etc/nagios/nagios.cfg,0 warning 才继续。 -
高可用与回滚
在 /etc/nagios/backup 做 git init,每次 api 写配置前自动 git commit -a -m "api-$(date +%s)";
回滚命令:git reset --hard HEAD~1 && systemctl reload nagios。
答案
现场给面试官一个可落地的 5 步脚本,边讲边写:
步骤 1:声明微信通知命令
cat > /etc/nagios/objects/commands/wechat.cfg <<'EOF'
define command{
command_name notify-service-wechat
command_line /usr/local/nagios/libexec/notify_wechat.py \
--hook_url="" \
--msg=" / "
}
EOF
步骤 2:准备 nagios-api 调用环境
export NAGIOS_API="https://nagios.internal.cn:8080"
export NAGIOS_USER="automation"
export NAGIOS_PASS=$(cat /run/secrets/nagios_api)
步骤 3:一次性创建联系人(幂等)
curl -u {NAGIOS_PASS} \
-X POST ${NAGIOS_API}/config/contact \
-H "Content-Type: application/json" \
-d '{
"contact_name": "oncall_wechat",
"alias": "值班微信",
"email": "oncall@company.cn",
"pager": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693a91f6-7a2f-4a78-85c3-9e2b9c8f1234",
"service_notification_commands": "notify-service-wechat",
"host_notification_commands": "notify-host-wechat",
"service_notification_period": "24x7",
"host_notification_period": "24x7"
}'
步骤 4:语法校验与重载
curl -u {NAGIOS_PASS} \
-X POST ${NAGIOS_API}/reload?check=1
步骤 5:验证
在测试主机上 主动触发随机 critical:
/usr/local/nagios/libexec/check_http -H 127.0.0.1 -p 9999
30 秒内企业微信群收到 “CRITICAL” 卡片即成功。
拓展思考
-
如果公司用飞书而非微信,只需把 notify_wechat.py 换成 notify_feishu.py,并在 pager 字段写飞书 hook;核心思路不变,体现“命令与通道解耦”。
-
面对千级联系人的扩容,nagios-api 逐条 POST 太慢,可改为:
- 本地批量生成 cfg 片段 → git push → CI 调用 /reload;
- 面试时提到“配置即代码”,能立即加分。
-
面试官可能追问“如何防止微信轰炸”:
答:在 contact 对象里加 service_notification_options=w,u,c,r,f 且 notification_interval=30,
并启用 nagios 的 escalation 模块,第一次 5 分钟微信,第二次 30 分钟短信,体现分层降噪思维。