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万亿美金豪赌 算…...
变量 varablie 声明- Rust 变量 let mut 声明与 C/C++ 变量声明对比分析
一、变量声明设计:let 与 mut 的哲学解析 Rust 采用 let 声明变量并通过 mut 显式标记可变性,这种设计体现了语言的核心哲学。以下是深度解析: 1.1 设计理念剖析 安全优先原则:默认不可变强制开发者明确声明意图 let x 5; …...
在HarmonyOS ArkTS ArkUI-X 5.0及以上版本中,手势开发全攻略:
在 HarmonyOS 应用开发中,手势交互是连接用户与设备的核心纽带。ArkTS 框架提供了丰富的手势处理能力,既支持点击、长按、拖拽等基础单一手势的精细控制,也能通过多种绑定策略解决父子组件的手势竞争问题。本文将结合官方开发文档,…...

聊聊 Pulsar:Producer 源码解析
一、前言 Apache Pulsar 是一个企业级的开源分布式消息传递平台,以其高性能、可扩展性和存储计算分离架构在消息队列和流处理领域独树一帜。在 Pulsar 的核心架构中,Producer(生产者) 是连接客户端应用与消息队列的第一步。生产者…...

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,SRS管理页面端口是8080,可…...

华为OD机试-食堂供餐-二分法
import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...
鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序
一、开发环境准备 工具安装: 下载安装DevEco Studio 4.0(支持HarmonyOS 5)配置HarmonyOS SDK 5.0确保Node.js版本≥14 项目初始化: ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...

视频字幕质量评估的大规模细粒度基准
大家读完觉得有帮助记得关注和点赞!!! 摘要 视频字幕在文本到视频生成任务中起着至关重要的作用,因为它们的质量直接影响所生成视频的语义连贯性和视觉保真度。尽管大型视觉-语言模型(VLMs)在字幕生成方面…...
WEB3全栈开发——面试专业技能点P2智能合约开发(Solidity)
一、Solidity合约开发 下面是 Solidity 合约开发 的概念、代码示例及讲解,适合用作学习或写简历项目背景说明。 🧠 一、概念简介:Solidity 合约开发 Solidity 是一种专门为 以太坊(Ethereum)平台编写智能合约的高级编…...

《基于Apache Flink的流处理》笔记
思维导图 1-3 章 4-7章 8-11 章 参考资料 源码: https://github.com/streaming-with-flink 博客 https://flink.apache.org/bloghttps://www.ververica.com/blog 聚会及会议 https://flink-forward.orghttps://www.meetup.com/topics/apache-flink https://n…...
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
最近需要在离线机器上运行软件,所以得把软件用docker打包起来,大部分功能都没问题,出了一个奇怪的事情。同样的代码,在本机上用vscode可以运行起来,但是打包之后在docker里出现了问题。使用的是dialog组件,…...