Linux 发邮件磁盘空间监控(python)

Linux 发邮件磁盘空间监控(python),linuxpython

核心代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-


import smtplib
import os
import commands,time 
from email.mime.text import MIMEText
#from email import MIMEText
disk_free=os.popen('df -lh')
list_disk=disk_free.read()
mailto_list=["[email protected]","[email protected]","[email protected]","[email protected]"]
mail_host="smtp.139.com" 
mail_user="user"  
mail_pass="password"  
mail_postfix="[email protected]" 
use01=commands.getstatusoutput("df -lh|awk '{print $4}'|grep '%'|awk -F '%' '{print $1}'|grep -v Use")
use02=commands.getstatusoutput("df -lh|awk '{print $5}'|grep '%'|awk -F '%' '{print $1}'|grep -v Use")
getrecord=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $1}'")
gettime=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $2}'")


free01=use01[1]
free02=use02[1]+'\n'+use01[1]
new_time=time.strftime("%Y%m%d", time.localtime())


def send_mail(to_list,sub,content):
  me=mail_postfix
  msg = MIMEText(content,_subtype='plain',_charset='gb2312')
  msg['Subject'] = sub
  msg['From'] = me
  msg['To'] = ";".join(to_list)
  try:
    server = smtplib.SMTP()
    server.connect(mail_host)
    server.login(mail_user,mail_pass)
    server.sendmail(me, to_list, msg.as_string())
    server.close()
    return True
  except SyntaxError:
    pass
    return False
if __name__ == '__main__':
    if free02>30:
        id=0
        if new_time>gettime[1]:
            while 1:
                getrecord=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $1}'")
                id=id+1
                '''
                jl=open('/home/oracle/script/dd.log')
                record=jl.read()
                '''
                line_l=str(id)+' '+new_time




                df=open('/home/oracle/script/mail.log','w')
                df.writelines(line_l)
                df.close()

                if send_mail(mailto_list,"hello",list_disk):
                    print "发送成功"
                else:
                    print "发送失败"
                if getrecord[1]>0:
                    break
        else:
            line_m=str(0)+' '+new_time
            free=open('/home/oracle/script/mail.log','w')
            free.writelines(line_m)
            free.close()

发邮件磁盘空间监控(python),linuxpython
核心代码: #!/usr/bin/python# -*- coding: UTF-8 -*-import
smtplibimport osimport commands,time from email.mime.text imp…

核心代码:

本文实例为大家分享了python3磁盘空间监控的具体代码,供大家参考,具体内容如下

echo 192.168.10.69>>ip.list
-------------------------------------------
#!/bin/bash
#注意if和[]之间的空格
rm -f ~/fanr/shell/DiskUsageAlert/out.print
out=$(cat ~/fanr/shell/DiskUsageAlert/ip.list)

echo $out
for _IP in $out
do
        ssh root@$_IP df | grep -vE "none|devfs"|awk '{if(NR>=2 && int($5)>100) print "'$_IP'" ":disk at " $6 " usage is "$5 " large than 90%" }' >> ~/fanr/shell/DiskUsageAlert/out.print

done

print=$(cat ~/fanr/shell/DiskUsageAlert/out.print)

echo $print
if [ "$print" != "" ]
#if[ -s "~/fanr/shell/DiskUsageAlert/out.print" ]
then
        echo 11
        #echo $print| mail -s"Disk Usage Alerter" fai@tgn.com
fi
--------------------------------------------------------------------------------------
crontab DiskUsageAlert.crontab
cat DiskUsageAlert.crontab
#每5分钟运行一次
*/5 * * * * sh /root/fanr/shell/DiskUsageAlert/DiskUsageAlter.sh

#!/bin/sh
#监控磁盘空间使用情况
#Written by Clement changed name Goni
#Http://chameleon.icpcn.com
scriptdir=/root/shell/disk_jk
logdir=$scriptdir/log
if [ -d $logdir ]
then
echo “$logdir is exist~!”
else
mkdir -p $logdir
fi
for disk in `df -h|grep “%” |sed
‘s/%//g’|grep -v “已用”|awk ‘{print $(NF-1)}’ `

\#根据自己系统安装的语言环境进行判断是否修改“已用”/“use”?
do
if [ “$disk” -gt “80” ]
#当然你可以排除一些不需要进行判断的磁盘空间,或指定的磁盘空间
then
echo “XX IP 服务器磁盘空间需要清理了” >$logdir/disk_alert.log
fi
done
if [ -s $logdir/disk_alert.log ]
then
cat $logdir/disk_alert.log |mail -s “`date +%Y-%m-%d` XX IP
的磁盘使用率已经达到80%,需要清理了~” xx@gmail.com
fi
#sleep 5
rm -fr $logdir/disk_alert.log

#!/usr/bin/python
# -*- coding: UTF-8 -*-


import smtplib
import os
import commands,time 
from email.mime.text import MIMEText
#from email import MIMEText
disk_free=os.popen('df -lh')
list_disk=disk_free.read()
mailto_list=["2880329185@qq.com","2881280685@qq.com","2880089704@qq.com","2880329180@qq.com"]
mail_host="smtp.139.com" 
mail_user="user"  
mail_pass="password"  
mail_postfix="jljgl@.com" 
use01=commands.getstatusoutput("df -lh|awk '{print $4}'|grep '%'|awk -F '%' '{print $1}'|grep -v Use")
use02=commands.getstatusoutput("df -lh|awk '{print $5}'|grep '%'|awk -F '%' '{print $1}'|grep -v Use")
getrecord=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $1}'")
gettime=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $2}'")


free01=use01[1]
free02=use02[1]+'\n'+use01[1]
new_time=time.strftime("%Y%m%d", time.localtime())


def send_mail(to_list,sub,content):
  me=mail_postfix
  msg = MIMEText(content,_subtype='plain',_charset='gb2312')
  msg['Subject'] = sub
  msg['From'] = me
  msg['To'] = ";".join(to_list)
  try:
    server = smtplib.SMTP()
    server.connect(mail_host)
    server.login(mail_user,mail_pass)
    server.sendmail(me, to_list, msg.as_string())
    server.close()
    return True
  except SyntaxError:
    pass
    return False
if __name__ == '__main__':
    if free02>30:
        id=0
        if new_time>gettime[1]:
            while 1:
                getrecord=commands.getstatusoutput("cat /home/oracle/script/mail.log|awk '{print $1}'")
                id=id+1
                '''
                jl=open('/home/oracle/script/dd.log')
                record=jl.read()
                '''
                line_l=str(id)+' '+new_time




                df=open('/home/oracle/script/mail.log','w')
                df.writelines(line_l)
                df.close()

                if send_mail(mailto_list,"hello",list_disk):
                    print "发送成功"
                else:
                    print "发送失败"
                if getrecord[1]>0:
                    break
        else:
            line_m=str(0)+' '+new_time
            free=open('/home/oracle/script/mail.log','w')
            free.writelines(line_m)
            free.close()

软硬件环境

参考:

图片 1

您可能感兴趣的文章:

  • python3监控CentOS磁盘空间脚本
  • python3实现磁盘空间监控

python3
apscheduler

 linux 自动执行
crontab学习笔记

前言

在做频繁操作磁盘的python项目时,经常会碰到磁盘空间不足的情况,这个时候,工程应该要有自己的处理模块,当磁盘利用率到达某个点时,发出警告并停止程序的运行。本文就利用Python3中的apscheduler模块来处理这样的问题。

代码实践

import os
import sys
import signal
import logging

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

# 开启磁盘空间检测
sched = BackgroundScheduler()

# 间隔5分钟开启一个检查
intervalTrigger = IntervalTrigger(minutes=5)

# 给检查任务设个id,方便任务的取消
sched.add_job(spaceMonitorJob, trigger=intervalTrigger, id='id_space_monitor')
sched.start()

# 禁止apscheduler相关信息屏幕输出
logging.getLogger('apscheduler.executors.default').propagate = False

方法spaceMonitorJob代码如下

def spaceMonitorJob():
 '''
 当磁盘(切片存储的目录)利用率超过90%,程序退出
 :return:
 '''

 try:
  st = os.statvfs('/')
  total = st.f_blocks * st.f_frsize
  used = (st.f_blocks - st.f_bfree) * st.f_frsize
 except FileNotFoundError:
  print('check webroot space error.')
  logger.error('check webroot space error.')

  # 移除任务,病关闭sched任务
  sched.remove_job(job_id='id_space_monitor')
  sched.shutdown(wait=False)
  sys.exit(-3)

 if used / total > 0.9:
  print('No enough space.')
  logger.debug('No enough space.')
  sched.remove_job(job_id='id_space_monitor')
  sched.shutdown(wait=False)

  # 杀掉进程
  os.killpg(os.getpgid(os.getpid()), signal.SIGKILL)

  # 退出
  exit(-3)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

  • 浅谈Python2、Python3相对路径、绝对路径导入方法
  • python3读取csv和xlsx文件的实例
  • Python3导入CSV文件的实例(跟Python2有些许的不同)
  • 详解python3中tkinter知识点
  • Python3用tkinter和PIL实现看图工具
  • Python3.4
    tkinter,PIL图片转换
  • Python3实现转换Image图片格式
  • python3实现域名查询和whois查询功能
  • python3实现windows下同名进程监控
  • python3监控CentOS磁盘空间脚本
  • Python3中详解fabfile的编写

You may also like...

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图