懒得排版了,随便看看吧
环境准备
1.服务器要求
一台运行哪吒探针的服务器
一台用于部署 Webhook 服务的服务器(可以与哪吒探针同一台)
Python 3.6+ 环境
2. 软件依赖
# 安装 Python 虚拟环境
sudo apt update
sudo apt install python3-venv python3-full -y
一.部署 Webhook 服务
1.创建项目目录
sudo mkdir -p /opt/nezha-webhook
cd /opt/nezha-webhook
2.创建 Python 虚拟环境
python3 -m venv venv
source venv/bin/activate
3.安装 Python 依赖
pip install flask requests
4.创建 Webhook 脚本
创建文件 /opt/nezha-webhook/nezha_webhook.py
#!/usr/bin/env python3
from flask import Flask, request, jsonify
import requests
import re
import json
import os
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('nezha-webhook')
app = Flask(__name__)
def format_metrics(raw_data):
"""格式化监控指标数据"""
formatted = {}
# 格式化CPU使用率(转为百分比)
cpu = raw_data.get('SERVER.CPU', '')
if cpu and cpu.replace('.', '').replace('-', '').isdigit():
try:
cpu_float = float(cpu)
formatted['cpu'] = f"{cpu_float:.1f}%"
except:
formatted['cpu'] = cpu
# 格式化内存使用量(字节转GB)
mem_bytes = raw_data.get('SERVER.MEM', '')
if mem_bytes and mem_bytes.isdigit():
try:
mem_gb = int(mem_bytes) / (1024 ** 3) # 字节转GB
formatted['mem'] = f"{mem_gb:.2f}GB"
except:
formatted['mem'] = mem_bytes
# 格式化网速(B/s 转 Mbps)
net_in = raw_data.get('SERVER.NETINSPEED', '')
net_out = raw_data.get('SERVER.NETOUTSPEED', '')
if net_in and net_in.isdigit():
try:
net_in_mbps = (int(net_in) * 8) / 1000000 # B/s to Mbps
formatted['net_in'] = f"{net_in_mbps:.2f}Mbps"
except:
formatted['net_in'] = net_in
if net_out and net_out.isdigit():
try:
net_out_mbps = (int(net_out) * 8) / 1000000 # B/s to Mbps
formatted['net_out'] = f"{net_out_mbps:.2f}Mbps"
except:
formatted['net_out'] = net_out
return formatted
@app.route('/', methods=['GET'])
def index():
"""根路径,用于测试服务是否运行"""
return jsonify({
"status": "running",
"service": "nezha-webhook",
"endpoints": {
"health": "/health (GET)",
"webhook": "/webhook/nezha (POST)"
}
})
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查端点"""
return jsonify({"status": "healthy", "service": "nezha-webhook"})
@app.route('/webhook/nezha', methods=['GET', 'POST'])
def nezha_webhook():
"""接收哪吒探针的Webhook"""
try:
logger.info(f"收到请求: {request.method} {request.url}")
if request.method == 'GET':
# 对于GET请求,返回使用说明
return jsonify({
"message": "请使用POST方法提交数据",
"example": {
"DATETIME": "2025-01-01 12:00:00.000000000 +0800 CST",
"SERVER.NAME": "服务器名称",
"SERVER.IP": "192.168.1.100",
"SERVER.CPU": "0.825516",
"SERVER.MEM": "2057187328",
"SERVER.NETINSPEED": "2851",
"SERVER.NETOUTSPEED": "1716",
"NEZHA": "报警消息内容"
}
})
# 处理POST请求
if request.is_json:
raw_data = request.get_json()
else:
raw_data = request.form.to_dict()
logger.info(f"收到的数据: {json.dumps(raw_data, ensure_ascii=False)}")
# 格式化时间
raw_time = raw_data.get('DATETIME', '')
time_match = re.match(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})', raw_time)
formatted_time = time_match.group(1) if time_match else raw_time
# 格式化监控指标
metrics = format_metrics(raw_data)
# 构建状态信息部分
status_info = ""
if metrics:
status_parts = []
if 'cpu' in metrics:
status_parts.append(f"💻 CPU使用率: {metrics['cpu']}")
if 'mem' in metrics:
status_parts.append(f"🧠 内存使用: {metrics['mem']}")
if 'net_in' in metrics and 'net_out' in metrics:
status_parts.append(f"📶 实时网速: 入 {metrics['net_in']} / 出 {metrics['net_out']}")
if status_parts:
status_info = "\n\n**📊 系统状态**\n" + "\n".join([f"- {item}" for item in status_parts])
# 钉钉机器人URL - 请替换为您的实际token!
dingtalk_token = "YOUR_DINGTALK_TOKEN_HERE" # 替换这里!
dingtalk_url = f"https://oapi.dingtalk.com/robot/send?access_token={dingtalk_token}"
# 使用markdown格式
message = {
"msgtype": "markdown",
"markdown": {
"title": "🚨 服务器状态报警 - 哪吒探针",
"text": f"""哪吒探针监控报警
### 🚨 服务器状态报警
**📋 基本信息**
- 🕐 时间:{formatted_time}
- 🖥️ 服务器:{raw_data.get('SERVER.NAME', '')}
- 📍 IP地址:{raw_data.get('SERVER.IP', '')}{status_info}
**📝 报警详情**
{raw_data.get('NEZHA', '')}
---
💡 请及时检查服务器状态"""
}
}
# 发送到钉钉
response = requests.post(dingtalk_url, json=message, headers={"Content-Type": "application/json"}, timeout=10)
logger.info(f"钉钉响应: {response.status_code} - {response.text}")
return jsonify({
"status": "success",
"dingtalk_response": response.text,
"formatted_metrics": metrics
})
except Exception as e:
logger.error(f"处理请求时出错: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
if __name__ == '__main__':
logger.info("启动哪吒Webhook服务...")
app.run(host='0.0.0.0', port=5000, debug=False)
5.设置脚本权限
chmod +x nezha_webhook.py
二、配置 Systemd 服务
1.创建 Systemd 服务文件
sudo nano /etc/systemd/system/nezha-webhook.service
内容如下:
[Unit]
Description=Nezha Webhook Service
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/nezha-webhook
Environment=PATH=/opt/nezha-webhook/venv/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=/opt/nezha-webhook/venv/bin/python /opt/nezha-webhook/nezha_webhook.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
2.启动并启用服务
sudo systemctl daemon-reload
sudo systemctl start nezha-webhook
sudo systemctl enable nezha-webhook
sudo systemctl status nezha-webhook
三、配置钉钉机器人
1.创建钉钉机器人
(1)打开钉钉群 → 设置 → 智能群助手
(2)添加机器人 → 自定义
(3)设置机器人名称和关键词
(4)获取 Webhook URL 中的 access_token
四、在哪吒面板中配置 Webhook
1.配置 Webhook 参数
(1)URL: http://您的服务器IP:5000/webhook/nezha
(2)请求方式: POST
(3)请求类型: JSON
2.配置请求头
{"Content-Type": "application/json"}
3.配置请求体
{
"DATETIME": "#DATETIME#",
"SERVER.NAME": "#SERVER.NAME#",
"SERVER.IP": "#SERVER.IP#",
"SERVER.CPU": "#SERVER.CPU#",
"SERVER.MEM": "#SERVER.MEM#",
"SERVER.NETINSPEED": "#SERVER.NETINSPEED#",
"SERVER.NETOUTSPEED": "#SERVER.NETOUTSPEED#",
"NEZHA": "#NEZHA#"
}
4.其余的自行按哪吒文档配置
五、测试和验证
# 检查服务状态
sudo systemctl status nezha-webhook
# 测试健康检查
curl http://localhost:5000/health
# 测试 Webhook 接口
curl -X POST -H "Content-Type: application/json" -d '{
"DATETIME": "2025-11-30 16:00:00.123456789 +0800 CST",
"SERVER.NAME": "测试服务器",
"SERVER.IP": "192.168.1.100",
"SERVER.CPU": "85.5",
"SERVER.MEM": "3221225472",
"SERVER.NETINSPEED": "6553600",
"SERVER.NETOUTSPEED": "3276800",
"NEZHA": "[测试] 这是一条测试报警消息"
}' http://localhost:5000/webhook/nezha
# 查看服务日志
sudo journalctl -u nezha-webhook -f
# 查看实时日志
sudo tail -f /var/log/syslog | grep nezha-webhook
六、维护和管理
1.服务管理命令
# 启动服务
sudo systemctl start nezha-webhook
# 停止服务
sudo systemctl stop nezha-webhook
# 重启服务
sudo systemctl restart nezha-webhook
# 查看服务状态
sudo systemctl status nezha-webhook
# 查看服务日志
sudo journalctl -u nezha-webhook -f
2.更新脚本
(1)修改 /opt/nezha-webhook/nezha_webhook.py
(2)重启服务:sudo systemctl restart nezha-webhook
效果展示
