当前位置: 首页 > 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…...

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…...

多云管理“拦路虎”:深入解析网络互联、身份同步与成本可视化的技术复杂度​

一、引言&#xff1a;多云环境的技术复杂性本质​​ 企业采用多云策略已从技术选型升维至生存刚需。当业务系统分散部署在多个云平台时&#xff0c;​​基础设施的技术债呈现指数级积累​​。网络连接、身份认证、成本管理这三大核心挑战相互嵌套&#xff1a;跨云网络构建数据…...

云计算——弹性云计算器(ECS)

弹性云服务器&#xff1a;ECS 概述 云计算重构了ICT系统&#xff0c;云计算平台厂商推出使得厂家能够主要关注应用管理而非平台管理的云平台&#xff0c;包含如下主要概念。 ECS&#xff08;Elastic Cloud Server&#xff09;&#xff1a;即弹性云服务器&#xff0c;是云计算…...

MFC内存泄露

1、泄露代码示例 void X::SetApplicationBtn() {CMFCRibbonApplicationButton* pBtn GetApplicationButton();// 获取 Ribbon Bar 指针// 创建自定义按钮CCustomRibbonAppButton* pCustomButton new CCustomRibbonAppButton();pCustomButton->SetImage(IDB_BITMAP_Jdp26)…...

CMake 从 GitHub 下载第三方库并使用

有时我们希望直接使用 GitHub 上的开源库,而不想手动下载、编译和安装。 可以利用 CMake 提供的 FetchContent 模块来实现自动下载、构建和链接第三方库。 FetchContent 命令官方文档✅ 示例代码 我们将以 fmt 这个流行的格式化库为例,演示如何: 使用 FetchContent 从 GitH…...

高防服务器能够抵御哪些网络攻击呢?

高防服务器作为一种有着高度防御能力的服务器&#xff0c;可以帮助网站应对分布式拒绝服务攻击&#xff0c;有效识别和清理一些恶意的网络流量&#xff0c;为用户提供安全且稳定的网络环境&#xff0c;那么&#xff0c;高防服务器一般都可以抵御哪些网络攻击呢&#xff1f;下面…...

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 提…...

【Oracle】分区表

个人主页&#xff1a;Guiat 归属专栏&#xff1a;Oracle 文章目录 1. 分区表基础概述1.1 分区表的概念与优势1.2 分区类型概览1.3 分区表的工作原理 2. 范围分区 (RANGE Partitioning)2.1 基础范围分区2.1.1 按日期范围分区2.1.2 按数值范围分区 2.2 间隔分区 (INTERVAL Partit…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

C# 表达式和运算符(求值顺序)

求值顺序 表达式可以由许多嵌套的子表达式构成。子表达式的求值顺序可以使表达式的最终值发生 变化。 例如&#xff0c;已知表达式3*52&#xff0c;依照子表达式的求值顺序&#xff0c;有两种可能的结果&#xff0c;如图9-3所示。 如果乘法先执行&#xff0c;结果是17。如果5…...