# -*- coding: utf-8 -*- import psutil import time from dingtalkchatbot.chatbot import DingtalkChatbot from datetime import datetime import os from os.path import join,getsize import io import re import json def listen_disc(cfg):#监控磁盘剩余空间webhook, secret disc = psutil.disk_usage('/') # 监控的磁盘路径 # print("磁盘空间使用了:%.1f GB,空闲:%.1fGB,总共:%.1f GB,使用率%.1f%%," % ( # disc.used / 1024 / 1024 / 1024, disc.free / 1024 / 1024 / 1024, # disc.total / 1024 / 1024 / 1024, disc.percent) + '\n') used_disc= disc.used / 1024 / 1024 / 1024 free_disc=disc.free / 1024 / 1024 / 1024 total_disc=disc.total / 1024 / 1024 / 1024 used_percent=disc.percent all="" #array=[] str_disc='' #all="磁盘空间使用了:"+str(round(used_disc,0))+"空闲:"+str(round(free_disc,0))+"总共:"+str(round(total_disc,0))+'\n' if float(disc.percent)>80: result='\n' title_name="磁盘空间使用率已达到"+str(used_percent)+'!\n' #disc_array=['/var/log','/opt/jmeter/apache-jmeter-5.4.3','/home/yan'] disc_array=cfg['disc_array'] print("disc_array is44:", disc_array) for i in disc_array: str_disc=str_disc+i.replace('[','').replace(']','')#去除[]符号 if ',' in str_disc:#以逗号为分隔符 arr=str_disc.split(',') print("arr is",arr) print("要监控的路径是:",arr) for disc1 in arr: begin='' size=0 for root,dirs,files in os.walk(disc1): size+=sum([getsize(join(root,name)) for name in files]) begin=begin+disc1+"=="+str(round(size/1024/1024/1024,1))+"GB"+ ';\n\n' #print("%s文件夹大小为:%.1fGB"%(disc1,size / 1024 / 1024 / 1024)) result=result+begin title_name=all+title_name+result print(title_name) dingtalk_robot(title_name,cfg) else: print("当前磁盘空间使用率合理") def dingtalk_robot(title_name,cfg): dogBOSS = DingtalkChatbot(cfg['webhook'], cfg['secrets']) red_msg = '<font color="#dd0000">%s</font>' % title_name #orange_msg = '<font color="#FFA500">级别:警告</font>' now_time = datetime.now().strftime('%Y.%m.%d %H:%M:%S') ip=cfg['ip'] url=cfg['url'] print("ip is:", ip) print("url is:", url) dogBOSS.send_markdown( title='来自服务器的提醒', #text="### **%s告警信息**\n %s\n\n **发送时间:** %s\n\n **磁盘空间清理:**[点击跳转] %s\n".format(ip,red_msg,now_time,url),is_at_all=False) text=f'### **{ip}告警信息**\n' f'{red_msg}\n\n' # f'**{orange_msg}**\n\n' f'**发送时间:** {now_time}\n\n' f'**磁盘空间清理:**[点击跳转]({url}) \n', is_at_all=False) def load_config():# 读取配置文件 pathfile = 'conf.txt' f = io.open(str(pathfile), "r") # 文件存放位置,自行修改 data = str(f.read()) f.close() dict = {} str_data = '' for i in data: str_data = str_data + i.strip('\n') # 去除换行符 if ';' in str_data: # 分号表示得到一个完整的数据,以这个数据为一个完整的整体进行切割 str_data = str_data[:-1] # 去除分号 arr = str_data.split('==') # 以==为分隔符切割数据 dict[arr[0]] = arr[1] # 按字典存储 str_data = '' # 重置变量用于下一个数据的切割 print(dict) return dict if __name__ == '__main__': cfg = load_config() # 读取配置文件 listen_disc(cfg) #执行监控
配置文件conf.txt,以分号为分隔符间隔每个参数;以双等号设置变量值;disc_array为列表格式的路径,把要监控的路径写里面,以英文格式的逗号分隔,例如:[a,b,c]
标签:1024,name,python,cfg,磁盘空间,disc,str,linux,print From: https://www.cnblogs.com/yan-test/p/17251257.html