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()

效果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python语言是一种非常适合网络编程的语言,并且具有很多网络编程库。要批量探测IP地址的存活性,我们可以使用Python的socket库。此外,要发送电子邮件,我们可以使用Python内置的smtplib模块。如果需要发送纯文本邮件,用SMTP邮件协议即可。如果需要发送HTML邮件,则需要使用MIME邮件协议。 批量探测IP地址存活性的方法是:使用ping命令,向目标主机发送ICMP封包,如果目标主机收到ICMP封包,它会回送一个ICMP封包,表示自己的存活状态。通过判断返回数据包中的状态码和延迟等指标,就可以判断目标主机的存活状态。 下面是一个简单的Python代码段,可以实现批量探测IP地址存活性和发送邮件告警: ```python #导入必要的模块 import subprocess import smtplib #定义目标IP地址列表 targets = ['192.168.1.1','192.168.1.2','192.168.1.3'] #遍历目标地址列表 for target in targets: #执行ping命令并获取结果 response = subprocess.Popen(['ping', '-c', '1', target], stdout=subprocess.PIPE).communicate()[0] #提取ping结果中的状态码 response_status = int(response.split('\n')[-3].split()[3]) #判断状态码并发送邮件告警 if response_status == 0: #如果存活,就不发送邮件 pass else: #如果不存活,就发送邮件 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('[email protected]', 'yourpassword') message = 'Subject: IP Address Alert\n\n' + target + ' is not responding to ping.' server.sendmail('[email protected]', '[email protected]', message) server.quit() ``` 在以上代码中,`targets`是要探测的IP地址的列表。通过遍历列表中的每个IP地址,使用`subprocess.Popen`函数执行ping命令并获取响应结果。判断响应结果中包含的状态码,如果为0,表示IP地址存活;如果为其他值,就发送邮件告警。要发送邮件,需要使用SMTP协议连接到email服务器,并调用`server.login`和`server.sendmail`函数。如果成功,就会发送一封电子邮件给指定的收件人。 总之,Python语言在批量探测IP地址存活性和发送邮件告警方面非常灵活。以上代码只是一个简单的例子,可以根据需要进行修改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值