Linux服务器磁盘及内存用量监控Python脚本(推送钉钉群通知)
文章目录
- Python 脚本
- 钉钉推送通知
- 定时任务
Python 脚本
# -*- coding: utf-8 -*-
import subprocessdef get_disk_usage():# 执行 df 命令获取磁盘使用情况df_process = subprocess.Popen(['df', '-h', '/'], stdout=subprocess.PIPE)output, _ = df_process.communicate()output = output.decode('utf-8')# 解析输出,获取磁盘总量和已使用占比total_space = Noneused_percentage = Nonelines = output.split('\n')for line in lines:if line.startswith('/dev'):parts = line.split()total_space = parts[1]used_percentage = parts[4]breakprint(f"磁盘总量: {total_space}, 已使用: {used_percentage}")return total_space, used_percentagedef check_disk_full(used_percentage, threshold_percent=90):# 检查磁盘是否快满了if used_percentage is not None:used_percentage = int(used_percentage[:-1]) # 去掉百分号并转换为整数if used_percentage >= threshold_percent:return Truereturn Falsedef get_memory_usage():try:# 执行 free 命令获取内存信息free_process = subprocess.Popen(['free', '-h'], stdout=subprocess.PIPE)output, _ = free_process.communicate()output = output.decode('utf-8')# 解析输出,获取内存总量和已使用占比lines = output.split('\n')for line in lines:if line.startswith('Mem:'):parts = line.split()total_memory = parts[1] # 内存总量used_memory = parts[2] # 已使用内存print(f"内存总量: {total_memory}, 已使用: {used_memory}")return total_memory, used_memoryreturn None, Noneexcept Exception as e:print(f"Error: {e}")return None, Nonedef check_memory_insufficient(total_memory, used_memory, threshold_percent=90):if total_memory is not None and used_memory is not None:# 解析内存值,去除单位,并将字符串转换为数值total_memory_value = float(total_memory[:-1])used_memory_value = float(used_memory[:-1])# 检查是否内存不足used_percentage = (used_memory_value / total_memory_value) * 100if used_percentage >= threshold_percent:return Truereturn Falseif __name__ == "__main__":# 获取磁盘使用情况total_space, used_percentage = get_disk_usage()if total_space and used_percentage:# 检查磁盘是否快满了(阈值默认为90%)if check_disk_full(used_percentage, threshold_percent=90):print("磁盘快满了!")else:print("未能获取磁盘使用情况。")# 获取内存使用情况total_memory, used_memory = get_memory_usage()if total_memory is not None and used_memory is not None:# 检查是否内存不足(默认阈值为90%)if check_memory_insufficient(total_memory, used_memory, threshold_percent=90):print("内存不足!")else:print("未能获取内存使用情况。")
- 输出结果
磁盘总量: 36G, 已使用: 65%
内存总量: 4.7G, 已使用: 1.0G
钉钉推送通知
- 钉钉自定义机器人Python脚本推送通知
- 钉钉推送配置与阈值
- ding-talk:secret: 'xxx'access-token: 'xxx'
- project:name: '项目名称'disk-threshold: 80memory-threshold: 90
- Python
pip3 install pyyaml
pip3 install requests
# -*- coding: utf-8 -*-
import subprocess
import yaml
import time
import hashlib
import base64
import hmac
import requests
from urllib.parse import quote
import socketdef get_disk_usage():# 执行 df 命令获取磁盘使用情况df_process = subprocess.Popen(['df', '-h', '/'], stdout=subprocess.PIPE)output, _ = df_process.communicate()output = output.decode('utf-8')# 解析输出,获取磁盘总量和已使用占比total_space = Noneused_percentage = Nonelines = output.split('\n')for line in lines:if line.startswith('/dev'):parts = line.split()total_space = parts[1]used_percentage = parts[4]breakprint(f"磁盘总量: {total_space}, 已使用: {used_percentage}")return total_space, used_percentagedef check_disk_full(used_percentage, threshold_percent=90):# 检查磁盘是否快满了if used_percentage is not None:used_percentage = int(used_percentage[:-1]) # 去掉百分号并转换为整数if used_percentage >= threshold_percent:return Truereturn Falsedef get_memory_usage():try:# 执行 free 命令获取内存信息free_process = subprocess.Popen(['free', '-h'], stdout=subprocess.PIPE)output, _ = free_process.communicate()output = output.decode('utf-8')# 解析输出,获取内存总量和已使用占比lines = output.split('\n')for line in lines:if line.startswith('Mem:'):parts = line.split()total_memory = parts[1] # 内存总量used_memory = parts[2] # 已使用内存print(f"内存总量: {total_memory}, 已使用: {used_memory}")return total_memory, used_memoryreturn None, Noneexcept Exception as e:print(f"Error: {e}")return None, Nonedef check_memory_insufficient(total_memory, used_memory, threshold_percent=90):if total_memory is not None and used_memory is not None:# 解析内存值,去除单位,并将字符串转换为数值total_memory_value = float(total_memory[:-1])used_memory_value = float(used_memory[:-1])# 检查是否内存不足used_percentage = (used_memory_value / total_memory_value) * 100if used_percentage >= threshold_percent:return Truereturn Falsedef read_yaml(file_path):with open(file_path, 'r', encoding='utf-8') as file:try:data = yaml.safe_load(file)return dataexcept yaml.YAMLError as e:print(f"读取 YAML 文件时出错:{e}")return Nonedef get_local_ip():try:# 创建一个 UDP 套接字sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)sock.connect(('8.8.8.8', 80)) # 连接 Google DNS# 获取本地 IP 地址local_ip = sock.getsockname()[0]return local_ipexcept Exception as e:print(f"Error: {e}")return Nonedef dingTalkSign(dingTalkSecret):# 获取当前时间戳,并将其转换为毫秒级timestamp = int(time.time() * 1000)# 将时间戳和钉钉应用的密钥拼接在一起,将拼接后的字符串转换为字节数组signBefore = ('%s\n%s' % (timestamp, dingTalkSecret)).encode('utf-8')# 用HMAC-SHA256算法对字节数组进行签名hsha256 = hmac.new(dingTalkSecret.encode('utf-8'), signBefore, hashlib.sha256)# 将签名进行Base64编码,将编码后的签名进行URL编码sign = quote(base64.b64encode(hsha256.digest()))return {"timestamp": timestamp, "sign": sign}def sendMessage(dingTalkUrl='', dingTalkSecret=None, message='', atMobiles=[], isAtAll=False):print("发送内容:", message, atMobiles, isAtAll)json = {"msgtype": "text","text": {"content": message,},"at": {"atMobiles": atMobiles,"isAtAll": isAtAll}}sign = dingTalkSign(dingTalkSecret)response = requests.post(url=dingTalkUrl, params=sign, json=json)print("响应内容:", response.json())if __name__ == "__main__":local_ip = get_local_ip()file_data = read_yaml("config.yml")if file_data:for entry in file_data:if 'ding-talk' in entry:dingTalkSecret = entry['ding-talk']['secret']access_token = entry['ding-talk']['access-token']if dingTalkSecret is None:print("未配置钉钉机器人密钥")if access_token is None:print("未配置钉钉机器人Token")else:# 自定义机器人推送地址dingTalkUrl = f"https://oapi.dingtalk.com/robot/send?access_token={access_token}"if dingTalkSecret is not None and 'project' in entry:project_name = entry['project']['name']disk_threshold = entry['project']['disk-threshold']memory_threshold = entry['project']['memory-threshold']# 获取磁盘使用情况total_space, used_percentage = get_disk_usage()total_memory, used_memory = get_memory_usage()if (total_space and used_percentage) or (total_memory and used_memory):# 检查磁盘是否快满了(阈值默认为90%)if check_disk_full(used_percentage, threshold_percent=disk_threshold):sendMessage(dingTalkSecret=dingTalkSecret, dingTalkUrl=dingTalkUrl, isAtAll=True,message=f'项目:{project_name}\n内网:{local_ip}\n磁盘:{total_space} / {used_percentage} (总/已用)\n内存:{total_memory} / {used_memory} (总/已用)\n磁盘不足,请及时扩容!')# 检查是否内存不足(默认阈值为90%)if check_memory_insufficient(total_memory, used_memory, threshold_percent=memory_threshold):sendMessage(dingTalkSecret=dingTalkSecret, dingTalkUrl=dingTalkUrl, isAtAll=True,message=f'项目:{project_name}\n内网:{local_ip}\n磁盘:{total_space} / {used_percentage} (总/已用)\n内存:{total_memory} / {used_memory} (总/已用)\n内存不足,请及时扩容!')else:print("未能获取磁盘使用情况。")
定时任务
- 在线生成CRON:https://tool.lu/crontab
# 查看python3安装位置
which python3
# 添加定时任务
crontab -e
# 定时执行Python脚本,根据自己需求配置执行时间
20 9 * * * /usr/bin/python3 /u01/setup.py
相关文章:
Linux服务器磁盘及内存用量监控Python脚本(推送钉钉群通知)
文章目录 Python 脚本钉钉推送通知定时任务 Python 脚本 # -*- coding: utf-8 -*- import subprocessdef get_disk_usage():# 执行 df 命令获取磁盘使用情况df_process subprocess.Popen([df, -h, /], stdoutsubprocess.PIPE)output, _ df_process.communicate()output out…...
Android13 Audio框架
一、Android 13音频代码结构 1、framework: android/frameworks/base 1.AudioManager.java :音频管理器,音量调节、音量UI、设置和获取参数等控制流的对外API 2.AudioService.java :音频系统服务(java层),…...
kafka消费者接收不到消息
背景: 对kafka消息进行监听,生产者发了消息,但是消费端没有接到消息,监听代码 消费端,kafka配置 spring.kafka.bootstrap-serverskafka.cestc.dmp:9591 spring.kafka.properties.sasl.jaas.configorg.apache.kafka.…...
Python如何从SQL Server存取数据?
在Python中,你可以使用各种库来连接和操作 SQL Server 数据库。一种常用的库是pyodbc,它是一个用于连接到各种数据库的开源 Python 库,包括 SQL Server。以下是连接到 SQL Server 并存取数据的基本步骤: 1、安装 pyodbc 库&#…...
学校机房Dev c++解决中文乱码问题
工具->编译选项->勾选 编译时加入以下命令 -fexec-charsetGBK -finput-charsetUTF-8 显示中文:工具->编辑器选项->去掉第一个的勾勾。...
基于java+springboot景区行李寄存管理系统设计和实现
基于javaspringboot景区行李寄存管理系统设计和实现 博主介绍:多年java开发经验,专注Java开发、定制、远程、文档编写指导等,csdn特邀作者、专注于Java技术领域 作者主页 央顺技术团队 Java毕设项目精品实战案例《1000套》 欢迎点赞 收藏 ⭐留言 文末获取…...
03-grafana的下拉列表选项制作-grafana的变量
一、准备环境 为了实现下拉列表筛选的样例,我们监控两个linux节点; 目前,我们已经有了一个节点了,再添加一个; 二、grafana的仪表盘变量 如果想给仪表盘自定义下拉列表,那么,需要设置变量&#…...
Linux网络编程—— IO多路复用
Linux网络编程—— IO多路复用 1. I/O 多路复用(I/O多路转接)1.1 常见的几种I/O模型 2. select3. poll4. epoll :star: 1. I/O 多路复用(I/O多路转接) I/O 多路复用 使得程序能 同时监听 多个文件描述符,能够提高程序的…...
C++进阶(二) 多态
一、多态的概念 多态的概念:通俗来说,就是多种形态, 具体点就是去完成某个行为,当不同的对象去完成时会 产生出不同的状态。举个栗子:比如买票这个行为,当普通人买票时,是全价买票;学…...
【C++】set、multiset与map、multimap的使用
目录 一、关联式容器二、键值对三、树形结构的关联式容器3.1 set3.1.1 模板参数列表3.1.2 构造3.1.3 迭代器3.1.4 容量3.1.5 修改操作 3.2 multiset3.3 map3.3.1 模板参数列表3.3.2 构造3.3.3 迭代器3.3.4 容量3.3.5 修改操作3.3.6 operator[] 3.4 multimap 一、关联式容器 谈…...
外包干了6个月,技术退步明显
先说一下自己的情况,本科生,19年通过校招进入广州某软件公司,干了接近4年的功能测试,今年年初,感觉自己不能够在这样下去了,长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测试…...
3. springboot中集成部署vue3
1. vue3构建 构建命令 npm run build, 构建的结果在disc目录: 2. springboot集成 2.1 拷贝vue3构建结果到springboot resources/static目录 2.2 springboot pom依赖 添加thymeleaf依赖 <dependency><groupId>org.springframework.boot</…...
问题
今天遇到数组开太大问题: 数组放在main函数里面,表示该数组是局部变量,不是全局变量,所以该数组是开在栈上,而栈的空间往往比较小,所以二维数组定义太大会导致爆栈。 全局变量全部存储在静态存储区。 在…...
#WEB前端
1.实验:vscode安装,及HTML常用文本标签 2.IDE:VSCODE 3.记录: (1)网页直接搜索安装vscode (2)打开vscode,在下图分别安装以下插件: Html Css Support …...
c语言经典测试题9
1.题1 #include <stdio.h> int main() { int i 1; sizeof(i); printf("%d\n", i); return 0; } 上述代码运行结果是什么呢? 我们来分析一下:其实这题的难点就是sizeof操作后i的结果是否会改变,首先我们创建了一个整型i&a…...
3d 舞蹈同步
目录 看起来很强大 unity驱动bvh跳舞: 脚飘动问题: bvh和播放关节对应关系 zxy格式 bvh和播放关节对应关系 zyx的对应关系: bvh播放器: 看起来很强大 GitHub - FORTH-ModelBasedTracker/MocapNET: We present MocapNET, a …...
win环境nginx实战配置详解
项目中经常使用nginx做负载均衡,接口路由、文件、文档的上传及下载、视频的代理播放等等,都离不开nginx的支持,今天我们分享一下其个使用场景。 1、配置文件 nd-nginx.conf 全局配置 #全局配置端,对全局生效,主要设置…...
数字化转型导师坚鹏:如何制定证券公司数字化转型年度培训规划
如何制定与实施证券公司数字化转型年度培训规划 ——以推动证券公司数字化转型战略落地为核心,实现知行果合一 课程背景: 很多证券公司都在开展数字化转型培训工作,目前存在以下问题急需解决: 缺少针对性的证券公司数字化转型…...
新王炸:文生视频Sora模型发布,能否引爆AI芯片热潮
前言 前方高能预警,Sora来袭! 浅析Sora的技术亮点 语言模型中构建关键词联系 视频素材分解为时空碎片 扩散模型DiT Not for play, But change world! OpenAI的宏大目标 未来已来,只是尚未流行 Sora的成本与OpenAI的7万亿美金豪赌 算…...
反向工程与模型迁移:打造未来商品详情API的可持续创新体系
在电商行业蓬勃发展的当下,商品详情API作为连接电商平台与开发者、商家及用户的关键纽带,其重要性日益凸显。传统商品详情API主要聚焦于商品基本信息(如名称、价格、库存等)的获取与展示,已难以满足市场对个性化、智能…...
【人工智能】神经网络的优化器optimizer(二):Adagrad自适应学习率优化器
一.自适应梯度算法Adagrad概述 Adagrad(Adaptive Gradient Algorithm)是一种自适应学习率的优化算法,由Duchi等人在2011年提出。其核心思想是针对不同参数自动调整学习率,适合处理稀疏数据和不同参数梯度差异较大的场景。Adagrad通…...
大语言模型(LLM)中的KV缓存压缩与动态稀疏注意力机制设计
随着大语言模型(LLM)参数规模的增长,推理阶段的内存占用和计算复杂度成为核心挑战。传统注意力机制的计算复杂度随序列长度呈二次方增长,而KV缓存的内存消耗可能高达数十GB(例如Llama2-7B处理100K token时需50GB内存&a…...
laravel8+vue3.0+element-plus搭建方法
创建 laravel8 项目 composer create-project --prefer-dist laravel/laravel laravel8 8.* 安装 laravel/ui composer require laravel/ui 修改 package.json 文件 "devDependencies": {"vue/compiler-sfc": "^3.0.7","axios": …...
视频行为标注工具BehaviLabel(源码+使用介绍+Windows.Exe版本)
前言: 最近在做行为检测相关的模型,用的是时空图卷积网络(STGCN),但原有kinetic-400数据集数据质量较低,需要进行细粒度的标注,同时粗略搜了下已有开源工具基本都集中于图像分割这块,…...
C++.OpenGL (14/64)多光源(Multiple Lights)
多光源(Multiple Lights) 多光源渲染技术概览 #mermaid-svg-3L5e5gGn76TNh7Lq {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-3L5e5gGn76TNh7Lq .error-icon{fill:#552222;}#mermaid-svg-3L5e5gGn76TNh7Lq .erro…...
嵌入式学习笔记DAY33(网络编程——TCP)
一、网络架构 C/S (client/server 客户端/服务器):由客户端和服务器端两个部分组成。客户端通常是用户使用的应用程序,负责提供用户界面和交互逻辑 ,接收用户输入,向服务器发送请求,并展示服务…...
并发编程 - go版
1.并发编程基础概念 进程和线程 A. 进程是程序在操作系统中的一次执行过程,系统进行资源分配和调度的一个独立单位。B. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。C.一个进程可以创建和撤销多个线程;同一个进程中…...
免费数学几何作图web平台
光锐软件免费数学工具,maths,数学制图,数学作图,几何作图,几何,AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...
MySQL 主从同步异常处理
阅读原文:https://www.xiaozaoshu.top/articles/mysql-m-s-update-pk MySQL 做双主,遇到的这个错误: Could not execute Update_rows event on table ... Error_code: 1032是 MySQL 主从复制时的经典错误之一,通常表示ÿ…...
