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

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层)&#xff0c…...

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 一、关联式容器 谈…...

Matlab/simulink微电网的PQ控制和下垂控制无缝切换建模仿真

​...

外包干了6个月,技术退步明显

先说一下自己的情况,本科生,19年通过校招进入广州某软件公司,干了接近4年的功能测试,今年年初,感觉自己不能够在这样下去了,长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测试…...

3. springboot中集成部署vue3

1. vue3构建 构建命令 npm run build&#xff0c; 构建的结果在disc目录&#xff1a; 2. springboot集成 2.1 拷贝vue3构建结果到springboot resources/static目录 2.2 springboot pom依赖 添加thymeleaf依赖 <dependency><groupId>org.springframework.boot</…...

问题

今天遇到数组开太大问题&#xff1a; 数组放在main函数里面&#xff0c;表示该数组是局部变量&#xff0c;不是全局变量&#xff0c;所以该数组是开在栈上&#xff0c;而栈的空间往往比较小&#xff0c;所以二维数组定义太大会导致爆栈。 全局变量全部存储在静态存储区。 在…...

#WEB前端

1.实验&#xff1a;vscode安装&#xff0c;及HTML常用文本标签 2.IDE&#xff1a;VSCODE 3.记录&#xff1a; &#xff08;1&#xff09;网页直接搜索安装vscode &#xff08;2&#xff09;打开vscode&#xff0c;在下图分别安装以下插件&#xff1a; Html Css Support …...

c语言经典测试题9

1.题1 #include <stdio.h> int main() { int i 1; sizeof(i); printf("%d\n", i); return 0; } 上述代码运行结果是什么呢&#xff1f; 我们来分析一下&#xff1a;其实这题的难点就是sizeof操作后i的结果是否会改变&#xff0c;首先我们创建了一个整型i&a…...

3d 舞蹈同步

目录 看起来很强大 unity驱动bvh跳舞&#xff1a; 脚飘动问题&#xff1a; bvh和播放关节对应关系 zxy格式 bvh和播放关节对应关系 zyx的对应关系&#xff1a; bvh播放器&#xff1a; 看起来很强大 GitHub - FORTH-ModelBasedTracker/MocapNET: We present MocapNET, a …...

win环境nginx实战配置详解

项目中经常使用nginx做负载均衡&#xff0c;接口路由、文件、文档的上传及下载、视频的代理播放等等&#xff0c;都离不开nginx的支持&#xff0c;今天我们分享一下其个使用场景。 1、配置文件 nd-nginx.conf 全局配置 #全局配置端&#xff0c;对全局生效&#xff0c;主要设置…...

数字化转型导师坚鹏:如何制定证券公司数字化转型年度培训规划

如何制定与实施证券公司数字化转型年度培训规划 ——以推动证券公司数字化转型战略落地为核心&#xff0c;实现知行果合一 课程背景&#xff1a; 很多证券公司都在开展数字化转型培训工作&#xff0c;目前存在以下问题急需解决&#xff1a; 缺少针对性的证券公司数字化转型…...

新王炸:文生视频Sora模型发布,能否引爆AI芯片热潮

前言 前方高能预警&#xff0c;Sora来袭&#xff01; 浅析Sora的技术亮点 语言模型中构建关键词联系 视频素材分解为时空碎片 扩散模型DiT Not for play, But change world! OpenAI的宏大目标 未来已来&#xff0c;只是尚未流行 Sora的成本与OpenAI的7万亿美金豪赌 算…...

测试微信模版消息推送

进入“开发接口管理”--“公众平台测试账号”&#xff0c;无需申请公众账号、可在测试账号中体验并测试微信公众平台所有高级接口。 获取access_token: 自定义模版消息&#xff1a; 关注测试号&#xff1a;扫二维码关注测试号。 发送模版消息&#xff1a; import requests da…...

零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?

一、核心优势&#xff1a;专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发&#xff0c;是一款收费低廉但功能全面的Windows NAS工具&#xff0c;主打“无学习成本部署” 。与其他NAS软件相比&#xff0c;其优势在于&#xff1a; 无需硬件改造&#xff1a;将任意W…...

k8s从入门到放弃之Ingress七层负载

k8s从入门到放弃之Ingress七层负载 在Kubernetes&#xff08;简称K8s&#xff09;中&#xff0c;Ingress是一个API对象&#xff0c;它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress&#xff0c;你可…...

Mybatis逆向工程,动态创建实体类、条件扩展类、Mapper接口、Mapper.xml映射文件

今天呢&#xff0c;博主的学习进度也是步入了Java Mybatis 框架&#xff0c;目前正在逐步杨帆旗航。 那么接下来就给大家出一期有关 Mybatis 逆向工程的教学&#xff0c;希望能对大家有所帮助&#xff0c;也特别欢迎大家指点不足之处&#xff0c;小生很乐意接受正确的建议&…...

【解密LSTM、GRU如何解决传统RNN梯度消失问题】

解密LSTM与GRU&#xff1a;如何让RNN变得更聪明&#xff1f; 在深度学习的世界里&#xff0c;循环神经网络&#xff08;RNN&#xff09;以其卓越的序列数据处理能力广泛应用于自然语言处理、时间序列预测等领域。然而&#xff0c;传统RNN存在的一个严重问题——梯度消失&#…...

连锁超市冷库节能解决方案:如何实现超市降本增效

在连锁超市冷库运营中&#xff0c;高能耗、设备损耗快、人工管理低效等问题长期困扰企业。御控冷库节能解决方案通过智能控制化霜、按需化霜、实时监控、故障诊断、自动预警、远程控制开关六大核心技术&#xff0c;实现年省电费15%-60%&#xff0c;且不改动原有装备、安装快捷、…...

从零实现STL哈希容器:unordered_map/unordered_set封装详解

本篇文章是对C学习的STL哈希容器自主实现部分的学习分享 希望也能为你带来些帮助~ 那咱们废话不多说&#xff0c;直接开始吧&#xff01; 一、源码结构分析 1. SGISTL30实现剖析 // hash_set核心结构 template <class Value, class HashFcn, ...> class hash_set {ty…...

QT: `long long` 类型转换为 `QString` 2025.6.5

在 Qt 中&#xff0c;将 long long 类型转换为 QString 可以通过以下两种常用方法实现&#xff1a; 方法 1&#xff1a;使用 QString::number() 直接调用 QString 的静态方法 number()&#xff0c;将数值转换为字符串&#xff1a; long long value 1234567890123456789LL; …...

今日学习:Spring线程池|并发修改异常|链路丢失|登录续期|VIP过期策略|数值类缓存

文章目录 优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器并发修改异常并发修改异常简介实现机制设计原因及意义 使用线程池造成的链路丢失问题线程池导致的链路丢失问题发生原因 常见解决方法更好的解决方法设计精妙之处 登录续期登录续期常见实现方式特…...

使用 SymPy 进行向量和矩阵的高级操作

在科学计算和工程领域&#xff0c;向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能&#xff0c;能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作&#xff0c;并通过具体…...