python3监控CentOS磁盘空间脚本

yipeiwu_com5年前Python基础

Python脚本监控CentOS磁盘空间,任何一个分区空间使用大于80%即发邮件给到指定邮箱。

monitor.py

#-*- coding: utf-8 -*- 
import socket 
import subprocess 
import smtplib 
from email.mime.text import MIMEText 
 
sender="xxx.xx@xxx.com" 
receiver= ["xxx.xx@xxx.com"] 
smtpHost="10.134.xxx.xxx" 
smtpPort="587" 
 
def get_ip(): 
  hostname = socket.getfqdn(socket.gethostname()) 
  ip = socket.gethostbyname(hostname) 
  return ip 
 
def send_mail(receiver,subject,content): 
  ip = get_ip() 
  msg = MIMEText(content,_subtype='plain',_charset='utf-8') 
  msg['Subject'] = subject 
  msg['From'] = 'CLOUD SERVER ' + ip 
  msg['To'] = ",".join(receiver) 
 
  try: 
    smtp = smtplib.SMTP(smtpHost,smtpPort) 
    #smtp.set_debuglevel(1) 
    smtp.docmd("HELO Server") 
    smtp.ehlo("ismetoad") 
    smtp.starttls() 
    smtp.helo("ismetoad") 
    smtp.sendmail(sender,receiver,msg.as_string()) 
    smtp.close() 
 
  except Exception as error: 
    print(error) 
 
def run_cmd(cmd): 
  process = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)   
  result_f,error_f = process.stdout,process.stderr 
  errors = error_f.read() 
  if errors: 
    pass 
  result = result_f.read().decode() 
  if result_f: 
    result_f.close() 
  if error_f: 
    error_f.close() 
  return result 
 
def disk_check(): 
  subject = '' 
  result = run_cmd(cmd) 
  content = '[root@vm-vc02-SR910 ~]# ' + cmd + '\n' + result 
  result = result.split('\n') 
  for line in result: 
    if 'G ' in line or 'M ' in line: 
      line = line.split() 
      for i in line: 
        if '%' in i and int(i.strip('%')) > 80: 
          subject = '[WARNING] SERVER FILESYSTEM USE% OVER ' + i + ', PLEASE CHECK!' 
  if subject: 
    send_mail(receiver,subject,content) 
    print('email sended') 
  else: 
    print('Everything is ok, keep on monitor.') 
               
if __name__ == '__main__': 
  cmd = 'df -h' 
  disk_check() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django基础学习之send_mail功能

前言 我们知道python中smtplib模块用于邮件的功能,而django对这个这模块进行封装,使得它使用起来十分简单。 django.core.mail就是django邮件的核心模...

python实现对列表中的元素进行倒序打印

python实现对列表中的元素进行倒序打印

1.案例要求: """有列表["a", "d", "f", "j","z","Z","1"],对列表进行倒序,打印结果为["1","Z","z","j","f","d",""a]""...

Python3.2中Print函数用法实例详解

本文实例讲述了Python3.2中Print函数用法。分享给大家供大家参考。具体分析如下: 1. 输出字符串 >>> strHello = 'Hello World...

Python 类与元类的深度挖掘 II【经验】

  上一篇解决了通过调用类对象生成实例对象过程中可能遇到的命名空间相关的一些问题,这次我们向上回溯一层,看看类对象本身是如何产生的。   我们知道 type() 方法可以查看一个对象的类...

Python面向对象编程基础实例分析

本文实例讲述了Python面向对象编程基础。分享给大家供大家参考,具体如下: 1、类的定义 Python中类的定义与对象的初始化如下,python中所有类的父类是object,需要继承。...