python监控脚本,监控CPU,磁盘报警时发送邮件

 我是一个python初学者,刚刚写的一个python脚本,希望大神指点。

#!/usr/bin/env python 
#encoding=utf-8
# filename=mail.py
import os
import statvfs
import sys
import time
import email
import smtplib
import poplib
vfs=os.statvfs("/home")
available=vfs[statvfs.F_BAVAIL]*vfs[statvfs.F_BSIZE]*1.0/(1024*1024*1024)
capacity=vfs[statvfs.F_BLOCKS]*vfs[statvfs.F_BSIZE]*1.0/(1024*1024*1024)
used=available/capacity*100
HOST_NAME='11.207.62.23'
cpu_time=os.popen("top -bi -n 2 -d 0.02|awk '{print $5}'|cut -b 1-4").read().split('\n\n\n')[1].split('\n')[2]
def disk_mail():
    try:
        handle = smtplib.SMTP('smtp.qq.com',25)
        handle.login('username','your password')
        msg = '\n%s,Insufficient Disk Space, available space %.2f%%, available disk space %.2fG, The total size of disk space %.2fG' % (HOST_NAME,used,available,capaci
ty)
        print msg.strip()
        handle.sendmail('from username','to username',msg)
        handle.close()
        return 1
    except smtplib.SMTPConnectError, e:
        print "error", e
        return 0
def cpu_mail():
    try:
        handle = smtplib.SMTP('smtp.qq.com',25)
        handle.login('username','your password')
        msg = '\n%s,Less CPU usage, The current availability for %s%% ' % (HOST_NAME,cpu_time)
        print msg.strip()
        handle.sendmail('from username','to username',msg)
        handle.close()
        return 1
    except smtplib.SMTPConnectError, e:
        print "error", e
        return 0
#def check_mail():
#    try:
#        p = poplib.POP3('pop.163.com')
#        p.user('username')
#        p.pass_('password')
#        ret = p.stat()
#        print ret
#        msglist = p.list()
#        print msglist[0]
#        for msg in msglist[1]:
#            print msg
#    except poplib.error_proto, e:
#        print 'login failed',e
#        sys.exit(1)
if available >1:
        disk_mail()
if cpu_time > 10:
        cpu_mail()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值