Python 检测当前系统的内存及硬盘资源,发送邮件告警通知(告警内容包含告警语句及网卡和系统版本时间)

颜色块

root@bogon:~ 2024-04-18 16:16:40# cat DefaultColor.py 
#########################################################################
#    File Name: DefaultColor.py
#    Author: eight
#    Mail: 18847097110@163.com 
#    Created Time: Thu 11 Apr 2024 10:25:31 PM CST
#########################################################################
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Color:
        END = '\033[0m'  # normal
        BOLD = '\033[1m'  # bold
        RED = '\033[1;91m'  # red
        GREEN = '\033[1;92m'  # green
        ORANGE = '\033[1;93m'  # orange
        BLUE = '\033[1;94m'  # blue
        PURPLE = '\033[1;95m'  # purple
        UNDERLINE = '\033[4m'  # underline
        CYAN = '\033[1;96m'  # cyan
        GREY = '\033[1;97m'  # gray
        BR = '\033[1;97;41m'  # background red
        BG = '\033[1;97;42m'  # background green
        BY = '\033[1;97;43m'  # background yellow

邮件代码

#########################################################################
#    File Name: inspection.py
#    Author: eight
#    Mail: 18847097110@163.com 
#    Created Time: Thu 11 Apr 2024 09:52:04 PM CST
#########################################################################
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import platform
import subprocess
import psutil
import DefaultColor
import smtplib
import socket
from email.mime.text import MIMEText
from email.header import Header


class MonitorCheck():

	def get_netcard(self):
		print("---------------------------------------------------------")
		# 检查网卡,定义一个列表,如果第一个值为2并且ip不是127.0.0.1 将其加入列表里
		netcard_info = []
		info = psutil.net_if_addrs()
		for netcard, ip_list in info.items():
			for item in ip_list:
				if item.family == 2 and item.address != '127.0.0.1':
					netcard_info.append((netcard, item.address))
		print("网络接口信息:")
		for netcard, ip in netcard_info:
			print(f"接口: {netcard}, IP: {ip}")
		return netcard_info                                                                

			

	def get_time(self):
		print("---------------------------------------------------------")
		system_time = time.strftime("%Y-%m-%d %X",time.localtime())
		print(f"当前系统时间是:{system_time}")
		print("---------------------------------------------------------")
		return system_time

	def basic_info(self):																																								  
		#调用系统命令输出结果,输出内容为字节,需要decode解码
		result = subprocess.run(["cat","/etc/os-release"], stdout=subprocess.PIPE)
		stdout = result.stdout.decode("utf-8")
		print("当前系统版本:")
		print()
		print(stdout)
		print("---------------------------------------------------------")
		
		return stdout

	def check_disk(self):																																															    
		#检查根分区的剩余容量:Avail
		disk_info = psutil.disk_usage('/')
		disk_free = disk_info.free / 1024 / 1024 / 1024
		print("系统根分区剩余:%s%.2f G%s" % (DefaultColor.Color.GREEN, disk_free, DefaultColor.Color.END))
		print("---------------------------------------------------------")
		if disk_free < 12:
			ip_info = self.get_netcard()
			time_info = self.get_time()
			version_info = self.basic_info()
			self.send_mail("硬盘", disk_free, ip_info, time_info, version_info)
	
	def check_memory(self):
		#检查内存total和free的空间
		memory_info = psutil.virtual_memory()
		memory_total = memory_info.total / 1024 / 1024 / 1024
		memory_free = memory_info.free / 1024 / 1024 / 1024
		print("系统总内存:%s%.2f G%s" % (DefaultColor.Color.GREEN, memory_total, DefaultColor.Color.END))
		print("系统可用内存:""%.2f" % memory_free,"G")
		print("---------------------------------------------------------")
		if memory_free < 3:
			ip_info = self.get_netcard()
			time_info = self.get_time()
			version_info = self.basic_info()
			self.send_mail("内存", memory_free, ip_info, time_info, version_info)
	def send_mail(self, resource, free_space, ip_info, time_info, version_info):
		# 设置发件人、收件人、主题、内容
		from_address = '18847097110@163.com'
		to_address = '963268595@qq.com'
		subject = f"系统{resource}告警"
		body = f"系统{resource}可用空间低于{'12GB' if resource == '硬盘' else '3GB'},当前可用空间:{free_space:.2f}GB,请及时处理.\n 系统IP:{ip_info}\n 系统时间:{time_info}\n系统版本:\n{version_info}  "
		# SMTP邮件服务器
		smtp_server = 'smtp.163.com'
		smtp_port = 25
											  
		# 发件人账号和密码
		username = '18847097110@163.com'
		password = 'your password'
														   
		# 创建邮件内容
		msg = MIMEText(body, 'plain', 'utf-8')
		msg['From'] = from_address
		msg['To'] = to_address
		msg['Subject'] = Header(subject, 'utf-8')
		server = None  # 初始化 server
																					 
		try:
		# 检查端口是否通畅
			sock = socket.create_connection((smtp_server, smtp_port), timeout=5)
			sock.close()
		# 连接邮件服务器并发送邮件
			server = smtplib.SMTP(smtp_server, smtp_port)
			server.login(username, password)
			server.sendmail(from_address, to_address, msg.as_string())
			print('Email send successfully!')
		#捕获socket的error
		except socket.error as e:
			print('Socket error occurred:', e)
		#捕获smtplib的error
		except smtplib.SMTPException as e:
			print('SMTP error occurred:', e)
		#捕获任何类型的异常
		except Exception as e:
			print('An error occurred:', e)
		#无论是否发生异常,此模块下的代码都会执行
		finally:
			if server is not None:																																																					server.quit()
																																																	
							    
if __name__ == '__main__':
	resp = MonitorCheck()
	resp.check_disk()
	resp.check_memory()

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值