From c2cbbd65670a53f2b62c5f0c4c9e617a143186f3 Mon Sep 17 00:00:00 2001 From: halliday Date: Mon, 27 Nov 2023 14:41:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=98=88=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 2 +- bin/get_system_info.py | 115 +++++++++++++++++++++++++++-------------- etc/check_config.yml | 11 +++- 3 files changed, 86 insertions(+), 42 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 021893f..5a4e330 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -9,7 +9,7 @@ "type": "python", "request": "launch", "program": "${file}", - "args": ["--send-mail=true"], + //"args": ["--send-mail=true"], "console": "integratedTerminal", "justMyCode": true } diff --git a/bin/get_system_info.py b/bin/get_system_info.py index 21e98cb..6873c6a 100644 --- a/bin/get_system_info.py +++ b/bin/get_system_info.py @@ -1,6 +1,6 @@ #!/usr/bin/python3file_today_path import _load -import psutil +import psutil import smtplib import argparse import yaml @@ -20,64 +20,74 @@ config_file_patch = path.parent.parent / "etc/check_config.yml" if not report_dir.exists(): # shutil.rmtree(data_dir) report_dir.mkdir() -#报告文件 -week=str(datetime.now().isocalendar()[1]) +# 报告文件 +week = str(datetime.now().isocalendar()[1]) file_name_week = "ComputerInfos-week-" + week + ".txt" -file_name_today="ComputerInfos-today.txt" +file_name_today = "ComputerInfos-today.txt" file_today_path = report_dir/file_name_today file_week_path = report_dir/file_name_week -#获取配置文件 -with open(config_file_patch,"r",encoding='utf-8') as fy: - config = yaml.safe_load(fy) -#print(config) +# 获取配置文件 +with open(config_file_patch, "r", encoding='utf-8') as fy: + config = yaml.safe_load(fy) +# print(config) + +need_sendmail = False + +# 发邮件 + -#发邮件 def send_mail(): - #发件人 + # 发件人 sender = 'mh@unamail.com' # 接收邮件,可以发给多人 receivers = config["receivers"] # 邮件主体 msg = MIMEMultipart() - #正文 - with open(str(file_today_path), "r", encoding='utf-8') as f: #打开文本 - msgdata = f.read() - message = "第{0}周,{1}资源使用情况检测已完成,本次检测内容如下所示,本周的所有信息请查看附件!\n{2}".format(week,get_IP(),msgdata) + # 正文 + with open(str(file_today_path), "r", encoding='utf-8') as f: # 打开文本 + msgdata = f.read() + message = "第{0}周,{1}资源使用情况检测已完成,本次检测内容如下所示,本周的所有信息请查看附件!\n{2}".format( + week, get_IP(), msgdata) msg.attach(MIMEText(message, 'plain', _charset="utf-8")) # 发送者 msg['From'] = Header(sender, 'utf-8') # 接收者 - msg['To'] = Header(receivers[0], 'utf-8') + msg['To'] = Header(receivers[0], 'utf-8') # 主题 - subject = '【长期任务】第{0}周{1}系统运行信息'.format(week,get_IP()) + subject = '【长期任务】第{0}周{1}系统运行信息'.format(week, get_IP()) msg['Subject'] = Header(subject, 'utf-8') - #附件信息 + # 附件信息 att = MIMEText(open(str(file_week_path), 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' - att["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name_week) + att["Content-Disposition"] = 'attachment; filename="{}"'.format( + file_name_week) msg.attach(att) try: smtpObj = smtplib.SMTP('10.10.110.102') smtpObj.sendmail(sender, receivers, msg.as_string()) - print ("邮件发送成功") + print("邮件发送成功") except smtplib.SMTPException: - print ("Error: 无法发送邮件") + print("Error: 无法发送邮件") -#写入文件 +# 写入文件 def save_txt(datas): - with open(str(file_today_path),'a+',encoding='utf-8',newline='') as file_txt: - [file_txt.write(str(item)+'\n') for item in datas] + with open(str(file_today_path), 'a+', encoding='utf-8', newline='') as file_txt: + [file_txt.write(str(item)+'\n') for item in datas] + +# 合并文件 + -#合并文件 def save_all_tex(): with open(file_today_path, 'rb') as f1, open(file_week_path, 'ab+') as f2: f2.write(f1.read()) # 获取本机磁盘使用率和剩余空间G信息 + + def get_disk_info(): # 循环磁盘分区 content = [] @@ -91,28 +101,38 @@ def get_disk_info(): free_disk_size = disk_info.free//1024//1024//1024 # 磁盘总空间,单位G total_disk_size = disk_info.total//1024//1024//1024 + # 检测是否超过阈值 + error_msg = "" + if disk_info.percent > config["Disk_MAX"]: + error_msg = "\n\t警告: {0}使用率超过{1},请及时处理!".format( + disk_name, str(config["Disk_MAX"])) + global need_sendmail + need_sendmail = True + # 当前磁盘使用率、剩余空间G和磁盘总空间信息 - info = "\t{0}\t使用率:{1}%, 剩余空间:{2}G, 总大小:{3}G".format(disk_name, str(disk_info.percent),free_disk_size,total_disk_size) + info = "\t{0}\t使用率:{1}%, 剩余空间:{2}G, 总大小:{3}G {4}".format( + disk_name, str(disk_info.percent), free_disk_size, total_disk_size, error_msg) # print(info) # 拼接多个磁盘的信息 content.append(info) print(content) save_txt(content) + # 获取某个目录的大小 -def get_dir_size(path): +def get_dir_size(path): list1 = [] for item in path.iterdir(): if item.is_file(): file_size = file_today_path.stat().st_size - list1.append(file_size) - str_tex=f"\t{item}的大小是{file_size}字节" + list1.append(file_size) + str_tex = f"\t{item}的大小是{file_size}字节" print(str_tex) save_txt([str_tex]) elif item.is_dir(): - #print(f"目录: {item}") + # print(f"目录: {item}") save_txt(['\t--------------']) - get_dir_size(item) + get_dir_size(item) str_dir_tex = '\t{0} 的大小为: {1:.4f} MB'.format(path, (sum(list1)/1024/1024)) print(str_dir_tex) @@ -122,18 +142,32 @@ def get_dir_size(path): # cpu信息 def get_cpu_info(): cpu_percent = psutil.cpu_percent(interval=1) - cpu_info = ["","CPU使用率:{0}%".format(cpu_percent),""] + # 检测是否超过阈值 + error_msg = "" + if cpu_percent > config["CPU_MAX"]: + error_msg = "\n\t警告: CPU使用率超过{0},请及时处理!".format(str(config["CPU_MAX"])) + global need_sendmail + need_sendmail = True + cpu_info = ["", "CPU使用率:{0}% {1}".format(cpu_percent, error_msg), ""] print(cpu_info) # return cpu_info save_txt(cpu_info) + # 内存信息 def get_memory_info(): virtual_memory = psutil.virtual_memory() used_memory = virtual_memory.used/1024/1024/1024 free_memory = virtual_memory.free/1024/1024/1024 memory_percent = virtual_memory.percent - memory_info = ["内存使用:{0:0.2f}G,使用率{1:0.1f}%,剩余内存:{2:0.2f}G".format(used_memory, memory_percent, free_memory),""] + # 检测是否超过阈值 + error_msg = "" + if memory_percent > config["Memory_MAX"]: + error_msg = "\n\t警告: 内存使用率超过{0},请及时处理!".format(str(config["Memory_MAX"])) + global need_sendmail + need_sendmail = True + memory_info = ["内存使用:{0:0.2f}G,使用率{1:0.1f}%,剩余内存:{2:0.2f}G {3}".format( + used_memory, memory_percent, free_memory,error_msg), ""] print(memory_info) # return memory_info save_txt(memory_info) @@ -155,13 +189,14 @@ def get_IP(): # elif snic.family.name == 'AF_INET6': # ipv6 = snic.address print(ipv4_list) - return(ipv4_list[0]) + return (ipv4_list[0]) + def main(): - #删除之前的文件 + # 删除之前的文件 if file_today_path.exists(): file_today_path.unlink() - #公共信息 + # 公共信息 commoninfo = [] if not file_week_path.exists(): t1 = "本周是第{0}周".format(week) @@ -171,7 +206,7 @@ def main(): commoninfo.append("检测时间: {0}".format(datetime.now())) commoninfo.append("检测IP: {0}".format(get_IP())) save_txt(commoninfo) - save_txt(["","磁盘使用情况:",""]) + save_txt(["", "磁盘使用情况:", ""]) get_disk_info() get_cpu_info() get_memory_info() @@ -179,17 +214,17 @@ def main(): directory_path = Path(path) save_txt(["{0}目录大小:".format(path)]) get_dir_size(directory_path) - - save_txt(['----------------------END----------------------------']) + save_txt(['----------------------END----------------------------']) if __name__ == '__main__': main() save_all_tex() - #默认不发邮件,通过参数控制 + # 默认不发邮件,通过参数控制 parser = argparse.ArgumentParser(description='send email') parser.add_argument("--send-mail", type=bool, default=False) args = parser.parse_args() - if args.send_mail: + # 超过阈值的和需要发邮件的 + if (args.send_mail or need_sendmail): send_mail() diff --git a/etc/check_config.yml b/etc/check_config.yml index 8999b19..8c5892a 100644 --- a/etc/check_config.yml +++ b/etc/check_config.yml @@ -1,8 +1,17 @@ #邮箱收件人,支持多个 receivers: - "mh@unamail.com" - - "ypy@unamail.com" +# - "ypy@unamail.com" #agent安装路径,windows路径要用双斜线,Linux不需要 agent_dir : "D:\\agent\\ubackup\\uagent\\logs" + +#资源阈值,超过这个值的会发告警 +#CPU使用率最大值 +CPU_MAX: 80 +#内存使用率最大值 +Memory_MAX: 80 +#磁盘使用率最大值 +Disk_MAX: 90 +