操作系统的版本信息:
[root@centos6 ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[root@centos6 ~]#
[root@centos6 ~]# uname -r
2.6.32-696.el6.x86_64
Python的版本信息:
[root@centos6 ~]# python3 --version
Python 3.6.8
发送告警邮件的脚本内容:
[root@centos6 ~]# cat xx.py
#coding=utf-8
import psutil
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
my_sender = 'j13680432782@126.com' #发件人邮箱账号
my_pass = 'Jackyxxxx' #发件人邮箱密码
my_name = 'zhuohua' #发件人邮箱昵称
receiver = '2270168881@qq.com' #收件人邮箱账号
receiver_name = 'Python' #收件人昵称
#本机主机名
hostname = 'Python.zhuohua.store'
#本机IP地址
ip = '192.168.168.130'
def func_mail(Key_1,Title_1):
try:
Message_1 = MIMEText(Key_1,'plain','utf-8')
Message_1['From'] = formataddr([my_name,my_sender])
Message_1['To'] = formataddr([receiver_name,receiver])
Message_1['Subject'] = Title_1
server=smtplib.SMTP_SSL("smtp.126.com",465) #发件人邮箱的SMTP服务器,端口是TCP 465
server.login(my_sender, my_pass)
server.sendmail(my_sender,[receiver,],Message_1.as_string())
server.quit()
except Exception as e:
print (f"发送邮件失败,原因: {e}")
else:
print("邮件发送成功")
if __name__ == '__main__':
#获取本机的CPU使用率
CPU_use_percent = psutil.cpu_percent(interval=2)
print(f"CPU使用率: {CPU_use_percent}")
Key_1 = f"主机{hostname}({ip})的CPU使用率达{CPU_use_percent}%"
Title_1 = "CPU使用率告警"
if CPU_use_percent > 80: #假如CPU使用率大于80%,就发送告警邮件
func_mail(Key_1,Title_1)
print("-" * 10)
#获取本机的内存使用率
Mem_use_percent = psutil.virtual_memory().percent
print(f"内存使用率: {Mem_use_percent}")
Key_1 = f"主机{hostname}({ip})的内存使用率达{Mem_use_percent}%"
Title_1 = "内存使用率告警"
if Mem_use_percent > 15: #假如内存使用率大于15%,就发送告警邮件
func_mail(Key_1,Title_1)
print("-" * 10)
#获取本机的根分区使用率
Root_used_percent = psutil.disk_usage("/")[3]
print(f"根分区使用率: {Root_used_percent}")
Key_1 = f"主机{hostname}({ip})的根分区使用率达{Root_used_percent}%"
Title_1 = "根分区使用率告警"
if Root_used_percent > 3: #假如根分区使用率大于3%,就发送告警邮件
func_mail(Key_1,Title_1)
设置脚本权限:
[root@centos6 ~]# chmod a+x xx.py
脚本运行的结果:
[root@centos6 ~]# python3 xx.py
CPU使用率: 0.5
----------
内存使用率: 41.3
邮件发送成功
----------
根分区使用率: 4.8
邮件发送成功
[root@centos6 ~]#
QQ邮箱收到的告警邮件:(每触发一条告警条件,126邮箱就发送一封告警邮件)
126邮箱发送这种邮件后,在“已发送”里是有记录的:
相关文章:
Linux使用第三方库psutil
Python3使用126邮箱的25端口发送邮件
CentOS8使用psutil+新浪邮箱使用465端口发送邮件 |