当前位置: 首页 > news >正文

prometheus+alertmanager+webhook钉钉机器人告警

版本:centos7.9 python3.9.5 alertmanager0.25.0 prometheus2.46.0

安装alertmanager prometheus 配置webhook

# 解压:
tar -xvf alertmanager-0.25.0.linux-amd64.tar.gz
tar -xvf prometheus-2.46.0.linux-amd64.tar.gz
mv alertmanager-0.25.0.linux-amd64 alertmanager
mv prometheus-2.46.0.linux-amd64 prometheus# 安装Python
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel
cd /app
wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz
tar -xvf Python-3.9.0.tgz
cd Python-3.9.0
./configure prefix=/usr/local/python3
make &&  make install
yum install gcc libffi-devel  openssl-devel -y  
ln -s /usr/local/python3/bin/python3.9 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.9 /usr/bin/pip3
pip3 install -U pip#配置webhook
pwd
/app/jiankong
cd /app
mdkir webhook
cd webhook
yum epel-release -y
yum install openssl11 openssl11-devel
pip3 install urllib3==1.26.15
pip3 install --upgrade cryptography
pip3 install --upgrade pyopenssl
pip3 install --upgrade requests
pip3 install flask
vim /app/webhook/main.py#!/usr/local/bin/python3
# coding: utf-8
import json
from datetime import datetime
import requests
from requests.exceptions import RequestException
from flask import Flask
from flask import requestapp = Flask(__name__)@app.route('/', methods=['POST'])
def send_wechat():if request.method == 'POST':post_data = request.get_data()data = json.loads(post_data.decode('utf-8'))for alert in data.get('alerts'):webchat(alert)return "success\n"@app.route('/dingtalk', methods=['POST'])
def send_dingtalk():if request.method == 'POST':post_data = request.get_data()data = json.loads(post_data.decode('utf-8'))access_token = 'dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxb'for alert in data.get('alerts'):content = dingtalk_msgformat(alert)dingding_sendmsg(access_token, content)return "success\n"@app.route('/prometheus_dingtalk', methods=['POST'])
def send_prodingtalk():if request.method == 'POST':post_data = request.get_data()data = json.loads(post_data.decode('utf-8'))access_token = '8xxxxxxxxxxxxxxxxxxxxxxxxxxx0'   #设置钉钉机器人for alert in data.get('alerts'):content = dingtalk_msgformat(alert)dingding_sendmsg(access_token, content)return "success\n"@app.route('/dingding_send', methods=['POST'])
def dingding_send():if request.method == 'POST':post_dingding_data = request.get_data()json_dingding_data = json.loads(post_dingding_data.decode('utf-8'))content = json_dingding_data["content"]access_token = json_dingding_data["access_token"]dingding_sendmsg(access_token, content)return "ok"def webchat(data):url = 'http://92.168.60.xxx:4567/send'users_list = []usernames = {}with open('/app/webhook/users', encoding='utf-8') as f:usernames = dict(line.strip().split(':') for line in f if line)      users_cn = data.get('annotations').get('sendUsers')for i in users_cn.split(','):if usernames.get(i):users_list.append(usernames.get(i))users = ','.join(users_list)message = '''status: %s
alertlevel: %s
alertname: %s
message: %s
startsAt: %s
endsAt: %s
消息发送时间: %s
消息发送给: %s''' % (data.get('status'), data.get('annotations').get('severity'), data.get('labels').get('alertname'),data.get('annotations').get('message'), data.get('startsAt'), data.get('endsAt'),datetime.now().isoformat(), users_cn)params = {'tos': users, 'content': message}requests.post(url=url, data=params)def dingtalk_msgformat(data):message = f'''status: {data.get('status')}
alertlevel: {data.get('annotations').get('severity')}
alertname: {data.get('labels').get('alertname')}
message: {data.get('annotations').get('message')}
startsAt: {data.get('startsAt')}
endsAt: {data.get('endsAt')}
消息发送时间:{datetime.now().isoformat()}
消息发送给:{data.get('annotations').get('sendUsers')}'''return messagedef dingding_sendmsg(access_token, content):headers = {'content-type': 'application/json','Accept': 'application/json;charset=utf-8',}payload = {"text": {"content": content},"at": {"atMobiles": "","isAtAll": False,},"msgtype": "text",}webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=%s' %access_tokentry:response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)response.raise_for_status()except RequestException as e:raise eif __name__ == '__main__':app.run(host='0.0.0.0', port=5000)#cat /etc/system/systemd/webhook.service
# 做成服务
[Unit]
Description= Webhook wechat for prometheus
After=network.target[Service]
#Restart=always
#RestartSec=30
#Type=simple
WorkingDirectory=/app/webhook
ExecStart=//usr/local/python3/bin/python3.9  /app/webhook/main.py[Install]
WantedBy=multi-user.target

配置alertmanager prometheus

# 配置数据存储目录
mkdir -p /data/prometheus/prometheus /data/prometheus/alertmanager
[root@rabbit4-64 prometheus]# ls
alertmanager  prometheus
[root@rabbit4-64 data]#  useradd prometheus
[root@rabbit4-64 data]# chown -R prometheus.prometheus  /data/prometheus  
[root@rabbit4-64 prometheus]# ll  
总用量 0
drwxr-xr-x. 2 prometheus prometheus 6 531 10:25 alertmanager
drwxr-xr-x. 2 prometheus prometheus 6 531 10:25 prometheus
[root@rabbit4-64 data]# # alertmanager配置
[root@rabbit3-63 alertmanager]# cat /app/jiankong/alertmanager/alertmanager.yml
global:resolve_timeout: 5mroute:group_by: ['alertname', 'cluster', 'service','instance']group_wait: 10sgroup_interval: 5srepeat_interval: 1hreceiver: 'wechat'
receivers:
- name: 'wechat'webhook_configs:- url: 'http://192.168.xxxxx:5000/prometheus_dingtalk'
inhibit_rules:- source_match:severity: 'critical'target_match:severity: 'warning'equal: ['alertname', 'dev', 'instance']# 设置成服务
[root@rabbit3-63 alertmanager]#  cat /etc/systemd/system/alertmanager.service 
[Unit]
Description=Prometheus Alert Manager
Documentation=https://prometheus.io/docs/introduction/overview/
After=network-online.target[Service]
User=prometheus
LimitNOFILE=65535
WorkingDirectory=/app/jiankong/alertmanager
ExecStart=/app/jiankong/alertmanager/alertmanager \--config.file=/app/jiankong/alertmanager/alertmanager.yml \--storage.path=/data/prometheus/alertmanager
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=60s[Install]
WantedBy=multi-user.target# prometheus配置
mkdir /app/jiankong/prometheus/rules
cd  /app/jiankong/prometheus/
chown -R prometheus.prometheus rules/
[root@rabbit4-64 prometheus]# cat prometheus.yml
global:scrape_interval:     60s # Set the scrape interval to every 15 seconds. Default is every 1 minute.evaluation_interval: 60s # Evaluate rules every 15 seconds. The default is every 1 minute.scrape_timeout: 55s
alerting:alertmanagers:- static_configs:- targets:- 192.168.70.xx:9093   # 设置alertmanager的地址rule_files:- '/app/jiankong/prometheus/rules/*.rules'  
scrape_configs:- job_name: 'prometheus'static_configs:- targets: ['localhost:9090']- job_name: "node"static_configs:- targets:["192.168.x0.xx:9100","192.168.x0.xx:9100",]# 做成服务
[root@localhost alertmanager]# cat /etc/systemd/system/prometheus.service 
[Unit]
Description=Prometheus Server
Documentation=https://prometheus.io/docs/introduction/overview/
After=network-online.target[Service]
User=prometheus
LimitNOFILE=65535
WorkingDirectory=/app/jiankong/prometheus
ExecStart=/app/jiankong/prometheus/prometheus  --log.level=info \--config.file=/app/jiankong/prometheus/prometheus.yml \--storage.tsdb.retention.time=10d \--storage.tsdb.path=/data/prometheus/prometheus
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=60s[Install]
WantedBy=multi-user.target# 配置相关规则
[root@rabbit4-64 rules]# cat up.rules 
groups:
- name: instance_statusrules:- alert: 系统或服务异常请运维紧急查看!!!expr: up == 0for: 30slabels:severity: pageannotations:sendUsers: "李处长"message: "{{$labels.instance}} 来自于 job {{$labels.job}} 已经采集失败超过五分钟。"severity: "Warning"[root@rabbit4-64 rules]# ls
linux_hosts.rules  up.rules
[root@rabbit4-64 rules]# cat up.rules 
groups:
- name: instance_statusrules:- alert: 系统或服务异常请运维紧急查看!!!expr: up == 0for: 30slabels:severity: pageannotations:sendUsers: "李处长"message: "{{$labels.instance}} 来自于 job {{$labels.job}} 已经采集失败超过五分钟。"[root@rabbit4-64 rules]# cat linux_hosts.rules 
groups:
- name: linux_host_statusrules:- alert: data_node_cpu_too_load_highexpr: (1 - avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m]))) * 100 > 60for: 5mlabels:severity: pageannotations:sendUsers: "李处长,陈处长"message: "{{ $labels.instance }} 来自于job {{ $labels.job }}  CPU 使用率连续五分钟超过 60%,当前值: {{ $value }} ,请检查主机应用!"severity: "Warning"- alert: node_filesystem_usage_hignexpr: node_filesystem_free_bytes{device !~'tmpfs', fstype!~'rootfs'} / node_filesystem_size_bytes < 0.15for: 5mlabels:severity: pageannotations:sendUsers: "李处长,陈处长"message: "{{ $labels.instance }} 来自于job {{ $labels.job }} 磁盘 {{$labels.device}} 挂载点 {{$labels.mountpoint}} 使用率超过 85%,当前值: {{ $value }} ,请检查主机磁盘!"severity: "Warning"- alert: data_node_memory_too_usage_highexpr: (node_memory_MemTotal_bytes - node_memory_MemFree_bytes - node_memory_Buffers_bytes - node_memory_Cached_bytes) / node_memory_MemTotal_bytes * 100 > 95for: 5mlabels:severity: pageannotations:sendUsers: "李处长,陈处长"message: "{{ $labels.instance }} 来自于job {{ $labels.job }} 内存使用率连续五分钟超过 95%, 当前值: {{ $value }} ,请检查主机应用!"severity: "Warning"- alert: yunclassroom_process_memory_use_highexpr: namedprocess_namegroup_memory_bytes{job="yunbanji_web",memtype="resident"}/1024/1024  > 4000for: 5mlabels:severity: pageannotations:sendUsers: "李处长,陈处长"message: "{{ $labels.instance }} 来自于进程 {{ $labels.groupname }} 内存使用率连续五分钟超过 4000M, 当前值: {{ $value }} ,请检查主机应用!"severity: "Warning"

启动相关服务

systemctl daemon-reload
systemctl start webhook
systemctl start alertmanager
systemctl start prometheus
systemctl status xxx  #查看状态[root@localhost jiankong]# netstat -nltp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:5000            0.0.0.0:*               LISTEN      60670/python3.9     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1014/sshd           
tcp6       0      0 :::9093                 :::*                    LISTEN      60467/alertmanager  
tcp6       0      0 :::9094                 :::*                    LISTEN      60467/alertmanager  
tcp6       0      0 :::9100                 :::*                    LISTEN      1013/node_exporter  
tcp6       0      0 :::22                   :::*                    LISTEN      1014/sshd           
tcp6       0      0 :::9090                 :::*                    LISTEN      60500/prometheus 

访问:ip:9090 ip:9094
在这里插入图片描述
在这里插入图片描述

测试:当其中一台挂掉了实现告警
在这里插入图片描述

相关文章:

prometheus+alertmanager+webhook钉钉机器人告警

版本&#xff1a;centos7.9 python3.9.5 alertmanager0.25.0 prometheus2.46.0 安装alertmanager prometheus 配置webhook # 解压&#xff1a; tar -xvf alertmanager-0.25.0.linux-amd64.tar.gz tar -xvf prometheus-2.46.0.linux-amd64.tar.gz mv alertmanager-0.25.0.linu…...

ctfshow 年CTF web

除夕 Notice: Undefined index: year in /var/www/html/index.php on line 16 <?phpinclude "flag.php";$year $_GET[year];if($year2022 && $year1!2023){echo $flag; }else{highlight_file(__FILE__); } 弱比较绕过很简单&#xff0c;连函数都没有直…...

原型链、闭包、手写一个闭包函数、 闭包有哪些优缺点、原型链继承

什么是原型链&#xff1f; 原型链是一种查找规则 为对象成员查找机制提供一个方向 因为构造函数的 prototype 和其实例的 __ proto __ 都是指向原型对象的 所以可以通过__proto__ 查找当前的原型对象有没有该属性, 没有就找原型的原型, 依次类推一直找到Object( null ) 为…...

linux中SSH_ASKPASS全局变量的作用

在工作中遇到一段代码&#xff0c;通过SSH_ASKPASS全局变量实现了ssh登录远程IP时的密码输入&#xff0c;chatgpt搜索了一下&#xff0c;其解释大致如下所示&#xff1a; SSH_ASKPASS 是一个环境变量&#xff0c;它在 SSH 客户端需要用户输入密码时起作用。当 SSH 客户端检测到…...

9 -力扣高频 SQL 50 题(基础版)

9 - 上升的温度 -- 找出与之前&#xff08;昨天的&#xff09;日期相比温度更高的所有日期的 id -- DATEDIFF(2007-12-31,2007-12-30); # 1 -- DATEDIFF(2010-12-30,2010-12-31); # -1select w1.id from Weather w1, Weather w2 wheredatediff(w1.recordDate,w2.recordDat…...

TCP的重传机制

TCP 是一个可靠的传输协议&#xff0c;解决了IP层的丢包、乱序、重复等问题。这其中&#xff0c;TCP的重传机制起到重要的作用。 序列号和确认号 之前我们在讲解TCP三次握手时&#xff0c;提到过TCP包头结构&#xff0c;其中有序列号和确认号&#xff0c; 而TCP 实现可靠传输…...

pg 数据库,获取时间字段值的具体小时,赋值给其他字段

目录 1 问题2 实现 1 问题 pg 数据库&#xff0c;有一个表&#xff0c;其中有2个字段 一个是时间字段obstime &#xff0c;一个是时次ltime字段&#xff0c;int 类型&#xff0c;现在这个表里面是obstime 里面有数据&#xff0c;ltime字段 没有数据&#xff0c;现在就是批量获…...

做视频号小店什么类目最容易爆单?其实,弄懂这三点就会选品了

大家好&#xff0c;我是电商花花。 我们做视频号小店做什么类目最容易爆单&#xff1f; 其实任何类目都有属于自己的受众人群和客户&#xff0c;都非常容易爆单&#xff0c;我们想要爆单&#xff0c;就要选对类目&#xff0c;选对产品。 视频号上所有的类目基本上可以分为标…...

Nginx作为下载站点

grep -Ev ^$|# /usr/local/nginx/conf/nginx.conf > /opt/nginx.txt cat /opt/nginx.txt > /usr/local/nginx/conf/nginx.conf用上面的指令提取最小化的配置文件 vim /usr/local/nginx/conf/nginx.conf [rootlocalhost ~]# cat /usr/local/nginx/conf/nginx.conf worker…...

vue3简单快速实现主题切换功能

⛰️个人主页: 蒾酒 &#x1f525;系列专栏&#xff1a;《vue3实战》 目录 内容概要 实现步骤 1.定义不同主题的css样式变量 2.入口main.ts中引入这个样式文件 3.主题样式css变量引用 4.设置默认主题样式 5.实现点击按钮主题切换 总结 最近发现了一个巨牛的人工智…...

国联易安:网络反不正当竞争,要防患于未然

据市场监管总局官网消息&#xff0c;为预防和制止网络不正当竞争&#xff0c;维护公平竞争的市场秩序&#xff0c;鼓励创新&#xff0c;保护经营者和消费者的合法权益&#xff0c;促进数字经济规范健康持续发展&#xff0c;市场监管总局近日发布《网络反不正当竞争暂行规定》&a…...

Linux 网络配置 01

基本命令 1、查看网络接口信息ifconfig ifconfig&#xff1a;当前设备正在工作的网卡&#xff0c;启动的设备 ifconfig -a &#xff1a;所网络设备 ifconfig信息解析&#xff1a; ens33: flags4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 192.168.10.10 n…...

快速入门C++正则表达式

正则表达式&#xff08;Regular Expression&#xff0c;简称 Regex&#xff09;是一种强大的文本处理工具&#xff0c;广泛用于字符串的搜索、替换、分析等操作。它基于一种表达式语言&#xff0c;使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。正则表达式不仅在…...

java —— 缓冲字符输入流/缓冲字符输出流

缓冲字符输入流/缓冲字符输出流是对字符输入流/字符输出流的加强&#xff0c;在使用中仍旧要借助于字符输入流/字符输出流才能完成实现。与字符输入流/字符输出流按照字符为单位进行输入/输出不同的是&#xff0c;缓冲字符输入流/缓冲字符输出流能够以行为单位进行读取和写入。…...

blender从视频中动作捕捉,绑定到人物模型

总共分为3个步骤&#xff1a; 1、从视频中捕捉动作模型 小K动画网-AIGC视频动捕平台 地址&#xff1a;https://xk.yunbovtb.com/ 需要注册 生成的FBX文件&#xff0c;不能直接导入到blender中&#xff0c; 方法有2种&#xff1a; 第一种&#xff1a;需要转换一下&#x…...

掘金滑块验证码安全升级,继续破解

去年发过一篇文章&#xff0c;《使用前端技术破解掘金滑块验证码》&#xff0c;我很佩服掘金官方的气度&#xff0c;不但允许我发布这篇文章&#xff0c;还同步发到了官方公众号。最近发现掘金的滑块验证码升级了&#xff0c;也许是我那篇文章起到了一些作用&#xff0c;逼迫官…...

数据结构练习题——Java实现

20240531-时间复杂度 1、消失的数字 方法一&#xff1a;位运算 两个数字一样的数组&#xff0c;其中一个数组中少了一个数字&#xff0c;定义一个变量分别异或两个数组&#xff0c;结果即为缺少的数字 class Solution {public int missingNumber(int[] nums) {int xor 0;int…...

行为设计模式之状态模式

文章目录 概述定义结构图 2.代码示例小结 概述 定义 状态模式(state pattern)的定义: 允许一个对象在其内部状态改变时改变它的行为。 对象看起来似乎修改了它的类。 状态模式就是用于解决系统中复杂对象的状态转换以及不同状态下行为的封装问题.。状态模式将一个对象的状态…...

找回以前的视频:技术与实践3个指南

你们有没有发现现在视频已经成为我们生活中不可或缺的一部分了&#xff1f;不管是在工作场合做演示、在学习时看教学视频&#xff0c;还是在休闲娱乐时追剧看电影&#xff0c;视频都扮演着超级重要的角色。 然而误删或手机故障的发生很可能将以前的视频清除。本文将深入探讨手…...

GCN 代码解析(一) for pytorch

Graph Convolutional Networks 代码详解 前言一、数据集介绍二、文件整体架构三、GCN代码详解3.1 utils 模块3.2 layers 模块3.3 models 模块3.4 模型的训练代码 总结 前言 在前文中&#xff0c;已经对图卷积神经网络&#xff08;Graph Convolutional Neural Networks, GCN&am…...

synchronized 学习

学习源&#xff1a; https://www.bilibili.com/video/BV1aJ411V763?spm_id_from333.788.videopod.episodes&vd_source32e1c41a9370911ab06d12fbc36c4ebc 1.应用场景 不超卖&#xff0c;也要考虑性能问题&#xff08;场景&#xff09; 2.常见面试问题&#xff1a; sync出…...

R语言AI模型部署方案:精准离线运行详解

R语言AI模型部署方案:精准离线运行详解 一、项目概述 本文将构建一个完整的R语言AI部署解决方案,实现鸢尾花分类模型的训练、保存、离线部署和预测功能。核心特点: 100%离线运行能力自包含环境依赖生产级错误处理跨平台兼容性模型版本管理# 文件结构说明 Iris_AI_Deployme…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

HTML 列表、表格、表单

1 列表标签 作用&#xff1a;布局内容排列整齐的区域 列表分类&#xff1a;无序列表、有序列表、定义列表。 例如&#xff1a; 1.1 无序列表 标签&#xff1a;ul 嵌套 li&#xff0c;ul是无序列表&#xff0c;li是列表条目。 注意事项&#xff1a; ul 标签里面只能包裹 li…...

srs linux

下载编译运行 git clone https:///ossrs/srs.git ./configure --h265on make 编译完成后即可启动SRS # 启动 ./objs/srs -c conf/srs.conf # 查看日志 tail -n 30 -f ./objs/srs.log 开放端口 默认RTMP接收推流端口是1935&#xff0c;SRS管理页面端口是8080&#xff0c;可…...

【单片机期末】单片机系统设计

主要内容&#xff1a;系统状态机&#xff0c;系统时基&#xff0c;系统需求分析&#xff0c;系统构建&#xff0c;系统状态流图 一、题目要求 二、绘制系统状态流图 题目&#xff1a;根据上述描述绘制系统状态流图&#xff0c;注明状态转移条件及方向。 三、利用定时器产生时…...

Module Federation 和 Native Federation 的比较

前言 Module Federation 是 Webpack 5 引入的微前端架构方案&#xff0c;允许不同独立构建的应用在运行时动态共享模块。 Native Federation 是 Angular 官方基于 Module Federation 理念实现的专为 Angular 优化的微前端方案。 概念解析 Module Federation (模块联邦) Modul…...

【C语言练习】080. 使用C语言实现简单的数据库操作

080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...

selenium学习实战【Python爬虫】

selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...

【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统

目录 游戏说明《宝可梦 Mesh GO》 —— 局域宝可梦探索Pokmon GO 类游戏核心理念应用场景Mesh 特性 宝可梦玩法融合设计游戏构想要素1. 地图探索&#xff08;基于物理空间 广播范围&#xff09;2. 野生宝可梦生成与广播3. 对战系统4. 道具与通信5. 延伸玩法 安全性设计 技术选…...