Python 磁盘监控邮件通知-mailgun

Python 磁盘监控邮件通知-mailgun

准备好 Mailgun api 信息,这里不做说明

脚本内容如下 vim  chk_disk.py

  1. #-*- coding: utf-8 -*-
  2. import socket
  3. import subprocess
  4. import smtplib
  5. from email.mime.text import MIMEText
  6. import datetime
  7. import os.path
  8. import time
  9. import logging
  10. import sys
  11. import requests
  12.  
  13. ##### 阿里云获取的内网故而没用这个
  14. def get_ip():
  15.     #hostname =  socket.getfqdn(socket.gethostname())
  16.     #ip = socket.gethostbyname(hostname)
  17.     ip = '127.0.0.1'
  18.     return ip
  19.  
  20. def send_mail(subject,content):
  21.     ip = get_ip()
  22.     return requests.post(
  23.         "https://api.mailgun.net/v3/mailgun domain/messages",
  24.         auth=("api", "mailgun api key"),
  25.         data={"from": "Mailgun Sandbox <[email protected]>",
  26.               "to": [“[email protected]”, “[email protected]”],
  27.               "subject": subject,
  28.               "text": content,
  29.               "html": "<html>It is so simple to send a message.<br/></html>"})
  30.  
  31. def run_cmd(cmd):
  32.     process = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  33.     result_f,error_f = process.stdout,process.stderr
  34.     errors = error_f.read()
  35.     if errors:
  36.         pass
  37.     result = result_f.read().decode()
  38.     if result_f:
  39.         result_f.close()
  40.     if error_f:
  41.         error_f.close()
  42.     return result
  43.  
  44. def disk_check():
  45.     subject = ''
  46.     result = run_cmd(cmd)
  47.     #content = 'root@backup-online:# ' + cmd + '\n' + result
  48.     content = 'SERVER IP : 127.0.0.1 \n'+'<br />'+'SERVER NAME : MyVPS \n'+'<br />'+'Project : MY TEST SERVER \n'+ '<br /><br />'
  49.     result = result.split('\n')
  50.     #print(result)
  51.     for line in result:
  52.         if 'G ' in line or 'M ' in line:
  53.             line = line.split()
  54.             for i in line:
  55.                 if '%' in i and int(i.strip('%')) > 90:
  56.                     subject = '[WARNING] SERVER FILESYSTEM USE% OVER ' + i + ', PLEASE CHECK!'
  57.                     content += '   '.join(line) + "\n <br />"
  58.     if subject:
  59.         send_mail(subject,content)
  60.         #print(content)
  61.         print('email sended')
  62.     else:
  63.         print('Everything is ok, keep on monitor.')
  64.  
  65. if __name__ == '__main__':
  66.     cmd = 'df -h'
  67.     disk_check()

发表回复

*您的电子邮件地址不会被公开。必填项已标记为 。

*
*