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万亿美金豪赌 算…...
Python原生AOT不是未来,是现在:某云厂商已将Django API服务AOT化,冷启动从1.8s→47ms,QPS提升4.3倍(完整CI/CD流水线配置)
第一章:Python原生AOT编译的演进逻辑与2026技术定位Python长期以来以解释执行和字节码(.pyc)为默认运行范式,其动态性与开发效率广受青睐,但启动延迟、内存开销与冷启动瓶颈在云原生边缘计算与嵌入式场景中日益凸显。原…...
Cursor无限制使用解决方案:cursor-free-vip完全指南
Cursor无限制使用解决方案:cursor-free-vip完全指南 【免费下载链接】cursor-free-vip [Support 0.45](Multi Language 多语言)自动注册 Cursor Ai ,自动重置机器ID , 免费升级使用Pro 功能: Youve reached your trial…...
SeqGPT-560M效果展示:无需训练的中文文本理解,财经/科技/娱乐分类实测案例
SeqGPT-560M效果展示:无需训练的中文文本理解,财经/科技/娱乐分类实测案例 今天我们来聊聊一个特别省心的AI工具——SeqGPT-560M。你可能听说过很多大模型,但训练它们往往需要准备数据、调参数,费时费力。SeqGPT-560M不一样&…...
实现高效邮件管理:Gmail桌面版部署与优化指南
实现高效邮件管理:Gmail桌面版部署与优化指南 【免费下载链接】gmail-desktop :postbox: Gmail desktop app for macOS, Windows & Linux (formerly Gmail Desktop) 项目地址: https://gitcode.com/gh_mirrors/gm/gmail-desktop 在当今数字化办公环境中&…...
Unity ObjectPool性能优化实战:从基础使用到高频对象管理
1. 为什么需要对象池?游戏性能的隐形杀手 在开发射击类游戏或AR应用时,最影响性能的往往不是华丽的特效,而是那些看似简单的对象创建与销毁操作。想象一下这样的场景:玩家每秒发射20发子弹,每发子弹存活2秒,…...
STM32F103C8T6实战:I2C驱动STP23L测距传感器与OLED显示优化
1. 项目背景与硬件选型 第一次接触STM32F103C8T6驱动STP23L测距传感器时,我完全没料到这个蓝色小模块会成为后续多个项目的核心组件。STP23L是一款基于TOF(飞行时间)原理的激光测距传感器,测量范围0.1-3米,精度可达1m…...
Qwen3-VL-WEBUI代理功能体验:让AI帮你操作电脑界面
Qwen3-VL-WEBUI代理功能体验:让AI帮你操作电脑界面 1. 引言:当AI学会"看"和"操作" 想象一下这样的场景:你正在远程指导父母使用一个新软件,但他们总是找不到"那个蓝色的下载按钮"在哪里。或者作为…...
GPEN图像肖像增强镜像实测:5分钟修复老照片,效果惊艳到哭
GPEN图像肖像增强镜像实测:5分钟修复老照片,效果惊艳到哭 1. 老照片修复的新选择 上周在整理家族相册时,我发现了一叠泛黄的老照片。这些珍贵的记忆因为年代久远,已经变得模糊不清,布满划痕和噪点。传统的修图软件要…...
Win10下VSCode安装全攻略:用户版vs系统版到底选哪个?
Win10下VSCode安装全攻略:用户版vs系统版深度解析与实战指南 Visual Studio Code(简称VSCode)作为微软推出的轻量级代码编辑器,凭借其强大的扩展性和跨平台特性,已成为开发者日常工作的标配工具。但在Windows 10环境下…...
Jimeng AI Studio(Z-Image Edition)与Python爬虫数据结合:自动化图像生成实战
Jimeng AI Studio(Z-Image Edition)与Python爬虫数据结合:自动化图像生成实战 1. 引言 你有没有遇到过这样的情况:每天需要为大量新闻资讯、产品信息或社交媒体内容配图,但手动设计耗时耗力,外包成本又太…...
