使用shell+python脚本实现系统监控并发送邮件

1、编辑shell脚本

[root@web03 ~/monitor_scripts]# cat inspect.sh 
#!/bin/bash

# 设置磁盘的阀值
disk_max=90

# 设置监控inode的分区
partition="/dev/sda3"

# 设置磁盘inode使用率的阀值
disk_inode_use=90

# 这是mem的阀值
mem_max_use=90

# CPU的空闲程度
cpu_less=10

function disk_space_info() {
    disk_used=$(df -h|grep /$|awk '{print $(NF-1)}'|cut -d% -f1)
    if [ $disk_used -gt $disk_max ];then
        Msg="TIME: $(date +%F-%T)
             HostName: $(hostname)
             IP: $(hostname -I)
             Info: 磁盘使用率超过80%,请及时处理!" 
        mail $Msg
    fi
}

function disk_inode_use() {
    inode_used=$(df -i /dev/sda3 |tail -1|awk -F'[ %]+' '{print $5}')
    if [ $inode_used -gt $disk_inode_use ];then
        Msg="TIME: $(date +%F-%T)
             HostName: $(hostname)
             IP: $(hostname -I)
             Info: ${partition}分区inode使用率超过${disk_inode_use}%,请及时处理!" 
        mail $Msg
    fi
}

function monitor_mem() {
    mem_used=$(free|grep Mem|awk '{printf ($3/$2)*100}'|cut -d. -f1)
    if [ $mem_used -gt $mem_max_use ];then
        Msg="TIME: $(date +%F-%T)
             HostName: $(hostname)
             IP: $(hostname -I)
             Info: 内存使用率超过${mem_max_use}%,请及时处理!"
        mail $Msg
    fi
}


function monitor_cpu() {
   cpu_used=$(vmstat 1 3|awk 'NR>=3{x=x+$(NF-2)} END {printf("%u",x/3)}')
   if [ $cpu_used -lt $cpu_less ];then
       Msg="TIME: $(date +%F-%T)
             HostName: $(hostname)
             IP: $(hostname -I)
             Info: cpu空闲率小于${cpu_less},请及时处理!"
        mail $Msg
   fi
}



disk_space_info
disk_inode_use
monitor_mem
monitor_cpu

2、编辑python脚本发送邮件

在使用的时候把mail文件授予x权限,再复制到/usr/bin,目录下当作命令执行。

[root@web03 ~/monitor_scripts]# cat mail 
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import smtplib
import email.mime.multipart
import email.mime.text

server = 'smtp.qq.com'   # 邮箱服务器
port = '25'              # 邮箱服务器端口

def sendmail(server,port,user,pwd,msg):
    smtp = smtplib.SMTP()
    smtp.connect(server,port)
    smtp.login(user, pwd)
    smtp.sendmail(msg['from'], msg['to'], msg.as_string())
    smtp.quit()
    print('邮件发送成功email has send out !')


if __name__ == '__main__':
    msg = email.mime.multipart.MIMEMultipart()
    
    msg['Subject'] = '系统监控告警邮件'   # 邮件标题
    msg['From'] = '1402122292@qq.com'     # 发送方的邮箱地址
    msg['To'] = 'gonglovepj@gmail.com'    # 目的邮箱地址
    
    user = '1402122292@qq.com'     # 登陆的用户
    pwd = 'folgrpnvvjfxjijc'       # 授权码
    
    content='%s
%s' %('
'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) #格式处理,专门针对我们的邮件格式

    txt = email.mime.text.MIMEText(content, _charset='utf-8')
    msg.attach(txt)

    sendmail(server,port,user,pwd,msg)