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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/719568.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/719568.shtml
英文地址,請注明出處:http://en.pswp.cn/news/719568.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Lua 篇(一)— 安裝運行Hello World

目錄 前言一、Lua 是什么?二、Lua和C#的區別三、安裝 LuaLinux 系統上安裝Mac OS X 系統上安裝Window 系統上安裝emmyluaRider 安裝(推薦) 四、Lua學習資料 前言 Lua 是一種輕量級的嵌入式腳本語言,它可以與 C 語言無縫集成,提供了強大的編程…

YOLOv6-Openvino和ONNXRuntime推理【CPU】

1 環境: CPU:i5-12500 Python:3.8.18 2 安裝Openvino和ONNXRuntime 2.1 Openvino簡介 Openvino是由Intel開發的專門用于優化和部署人工智能推理的半開源的工具包,主要用于對深度推理做優化。 Openvino內部集成了Opencv、Tens…

庫函數和頭文件

難道要求平方根也要自己寫一個&#xff1f; #include<iostream> #include<cmath>//頭文件<cmath>中包含許多數學庫函數 using namespace std; int main() {double a;cin>>a;if(a<0) {cout<<"Illegal input"<<endl;return 0;…

PHP語言常見面試題:在PHP中,如何聲明變量?變量的作用域是什么?

在PHP中&#xff0c;聲明變量非常直接和簡單。您只需要在變量名前加上$符號&#xff0c;然后為其分配一個值。這里有一個基本的例子&#xff1a; php復制代碼 <?php $variableName "Hello, World!"; // 聲明一個名為 $variableName 的變量&#xff0c;并賦值為…

DataGrip 2023:讓數據庫開發變得更簡單、更高效 mac/win

JetBrains DataGrip 2023是一款功能強大的數據庫IDE&#xff0c;專為數據庫開發和管理而設計。通過DataGrip&#xff0c;您可以連接到各種關系型數據庫管理系統(RDBMS)&#xff0c;并使用其提供的一組工具來查詢、管理、編輯和開發數據庫。 DataGrip 2023軟件獲取 DataGrip 2…

前端學習第七天-css常用樣式設置

達標要求 掌握元素的顯示與隱藏 熟練應用溢出的文字隱藏 熟練掌握版心和布局流程 1. 元素的顯示與隱藏 在CSS中有三個顯示和隱藏的單詞比較常見&#xff0c;我們要區分開&#xff0c;他們分別是 display visibility 和 overflow。 他們的主要目的是讓一個元素在頁面中消失…

94、利用多線程優化卷積運算

上一節簡單介紹了多線程的概念,同時也介紹了在使用多線程編程時,對于數據在線程間的切分,應該遵循的一個原則:那就是切分獨立的數據快,而不切分有數據依賴的數據塊。 最后還拋出了一個問題:對于卷積算法而言,你覺的切分哪個維度最合適呢? 卷積的切分 之前花了很多篇幅…

數據結構從入門到精通——鏈表

鏈表 前言一、鏈表1.1 鏈表的概念及結構1.2 鏈表的分類1.3 鏈表的實現1.4 鏈表面試題1.5 雙向鏈表的實現 二、順序表和鏈表的區別三、單項鏈表實現具體代碼text.htext.cmain.c單鏈表的打印空間的開辟鏈表的頭插、尾插鏈表的頭刪、尾刪鏈表中元素的查找鏈表在指定位置之前、之后…

LabVIEW齒輪傳動健康狀態靜電在線監測

LabVIEW齒輪傳動健康狀態靜電在線監測 隨著工業自動化的不斷發展&#xff0c;齒輪傳動作為最常見的機械傳動方式之一&#xff0c;在各種機械設備中發揮著至關重要的作用。然而&#xff0c;齒輪在長期運行過程中易受到磨損、變形等因素影響&#xff0c;進而影響整個機械系統的穩…

日常工作總結

日常工作總結 1000. JAVA基礎1. 泛型1.1 泛型和Object的區別 1100. Spring1. 常用注解1.1 ControllerAdvice注解1.2 緩存Cacheable 2. 常用方法2.1 BeanUtils.copyProperties的用法 3. 常用功能組件3.1 過濾器Filter 2000. Linux應用 1000. JAVA基礎 1. 泛型 1.1 泛型和Objec…

【爬蟲實戰】——Python爬取天氣信息

&#x1f349;CSDN小墨&曉末:https://blog.csdn.net/jd1813346972 個人介紹: 研一&#xff5c;統計學&#xff5c;干貨分享 ???????? 擅長Python、Matlab、R等主流編程軟件 ???????? 累計十余項國家級比賽獎項&#xff0c;參與研究經費10w、40w級橫向 文…

大模型推薦落地啦!融合知識圖譜,螞蟻集團發布!

引言&#xff1a;電商推薦系統的新突破 隨著電子商務平臺的蓬勃發展&#xff0c;推薦系統已成為幫助用戶在信息過載時代中篩選和發現產品的關鍵工具。然而&#xff0c;傳統的推薦系統主要依賴歷史數據和用戶反饋&#xff0c;這限制了它們在新商品推出和用戶意圖轉變時的有效性…

使用AspectJ進行面向切面編程(AOP)

第1章 引言 大家好&#xff0c;我是小黑&#xff0c;業務開發中&#xff0c;咱們經常會遇到這樣的情況&#xff1a;有些代碼幾乎在每個方法里都要用到&#xff0c;比如日志記錄、權限校驗、或者性能監測。如果每次都手動加入這些代碼&#xff0c;不僅效率低下&#xff0c;而且…

深入了解接口測試:方法、工具和關鍵考慮因素

接口測試是軟件測試中的一項重要工作&#xff0c;它涉及到系統與系統之間的交互點。接口可以是外部接口&#xff0c;也可以是內部接口&#xff0c;包括上層服務與下層服務接口以及同級接口。在接口測試中&#xff0c;我們需要確保接口能夠按照預期的方式進行通信和交互&#xf…

C++ 模擬OJ

目錄 1、1576. 替換所有的問號 2、 495. 提莫攻擊 3、6. Z 字形變換 4、38. 外觀數列 5、 1419. 數青蛙 1、1576. 替換所有的問號 思路&#xff1a;分情況討論 ?zs&#xff1a;左邊沒有元素&#xff0c;則僅需保證替換元素與右側不相等&#xff1b;z?s&#xff1a;左右都…

Java - List排序

List排序方法 主要有三種方法&#xff08;按推薦度排序&#xff09;&#xff1a; JDK8的streamComparator#compare()Comparable#compareTo() 法1&#xff1a;list的sort() package com.example.a;import java.util.ArrayList; import java.util.Comparator; import java.util…

pyqt5 QWebEngineView 重寫mousepressevent捕獲鼠標點擊事件,無響應

QWebEngineView 加載網頁后&#xff0c;重寫mousepressevent捕獲鼠標點擊事件&#xff0c;無響應原因是 QWebEngineView在加載界面后&#xff0c;被本身的child接收了該事件&#xff0c; 解決辦法&#xff1a;同過重載event&#xff0c;截取QEvent::ChildAdded事件 from PyQ…

islide2024免費版PPT插件下載

一、功能概覽 iSlide PPT插件是一款專為PowerPoint用戶設計的輔助工具&#xff0c;其功能全面且實用&#xff0c;主要包括但不限于以下幾點&#xff1a; 設計元素庫&#xff1a;提供豐富的設計元素&#xff0c;如主題、布局、圖標、配色等&#xff0c;用戶可以直接拖拽使用&a…

動態規劃|【雙指針】|611.有效三角形個數

題目 611. 有效三角形的個數 給定一個包含非負整數的數組 nums &#xff0c;返回其中可以組成三角形三條邊的三元組個數。 示例 1: 輸入: nums [2,2,3,4] 輸出: 3 解釋:有效的組合是: 2,3,4 (使用第一個 2) 2,3,4 (使用第二個 2) 2,2,3示例 2: 輸入: nums [4,2,3,4] 輸出…