python实现文件系统监控

背景: python实现Linux文件系统监控,当某个目录使用达到某个阈值的时候,自动发送文件告警

实现工具:

python 2.7

linux shell

ansible 2.5.0


代码实现:

# -*- coding:utf-8 -*-

import os
import commands
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header


'''
fsmon.sh 内容
#df -m|grep -v system
#df -m|grep sd|awk '{print $5}'|grep -Eo [0-9]+
hostname
df -m|grep sd

'''






def SendMail(mailContent):
    # 配置发送方和接收方
    sender = 'xxx@xxx.com'
    receiver = 'xxx@xxx.com' 
    # acc = 'xxx@xxx.com'

    subject = "Caution: Linux文件系统监控告警 !!"
    smtpserver = 'mail.xxxxx.com'
    username = 'oakefe'
    password = 'abcd1234'

    # 定义发送邮件的内容 和 主题
    mailContent = mailContent
    msg = MIMEText(mailContent, 'plain', 'utf-8')
    msg['From'] = Header(sender, 'utf-8')
    msg['To'] = Header(receiver, 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')

    # 执行发送动作
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(user=sender, password=password)
        # smtp.sendmail(from_addr=sender, to_addrs=receiver.split(',') + acc.split(','), msg=msg.as_string())
        smtp.sendmail(from_addr=sender, to_addrs=receiver.split(','), msg=msg.as_string())
        smtp.quit()
        print "告警邮件发送成功"
    except Exception, e:
        print "告警邮件发送失败" + str(e)


#################
### 主操作流程
#################

(status, output) = commands.getstatusoutput("ansible 10.1.19.6 -m script -a '/tmp/wmpmon/fsmon.sh'  --tree '/tmp'") #测试status

file = open("/tmp/10.1.19.6","r")
file_fact = json.loads(file.read(), 'utf-8')
#
# print file_fact

contentList = file_fact["stdout_lines"]

#主机名
hostname = contentList[0]

# [0] 挂载的磁盘 [4]使用百分比 [5]挂载的操作系统目录
#  /dev/sda1               1014    172   843   17% /boot

for i in range(1,len(contentList)):
    fileSystemFact = contentList[i].split()[0]
    totalFact = contentList[i].split()[1]
    usedFact = contentList[i].split()[2]
    freeFact = contentList[i].split()[3]
    usedPercentFact = contentList[i].split()[4].split("%")[0]
    mountedDirFact = contentList[i].split()[5]
    mailContent = u"主机名:" + hostname +u", 文件系统: "+  fileSystemFact + u",使用百分比: " + usedPercentFact + u"%,挂载目录:  " + mountedDirFact

    if int(usedPercentFact) >= 85:
        SendMail(mailContent)




















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值