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设计】。

相关文章

Python走楼梯问题解决方法示例

本文实例讲述了Python走楼梯问题解决方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 ''' 下楼问题。从楼上走到楼下共有...

在python中pandas读文件,有中文字符的方法

后面要加encoding='gbk' import pandas as pd datt=pd.read_csv('D:\python_prj_1\data_1.txt',encodi...

详解Python中的__new__、__init__、__call__三个特殊方法

__new__: 对象的创建,是一个静态方法,第一个参数是cls。(想想也是,不可能是self,对象还没创建,哪来的self) __init__ : 对象的初始化, 是一个实例方法,第一...

Python 确定多项式拟合/回归的阶数实例

Python 确定多项式拟合/回归的阶数实例

通过 1至10 阶来拟合对比 均方误差及R评分,可以确定最优的“最大阶数”。 import numpy as np import matplotlib.pyplot as plt f...

python中list常用操作实例详解

本文实例讲述了python中list常用操作。分享给大家供大家参考。具体分析如下: 1.定义list >>> li = ["a", "b", "mpilgrim",...