准备好 Mailgun api 信息,这里不做说明
脚本内容如下 vim chk_disk.py
- #-*- coding: utf-8 -*-
- import socket
- import subprocess
- import smtplib
- from email.mime.text import MIMEText
- import datetime
- import os.path
- import time
- import logging
- import sys
- import requests
- ##### 阿里云获取的内网故而没用这个
- def get_ip():
- #hostname = socket.getfqdn(socket.gethostname())
- #ip = socket.gethostbyname(hostname)
- ip = '127.0.0.1'
- return ip
- def send_mail(subject,content):
- ip = get_ip()
- return requests.post(
- "https://api.mailgun.net/v3/mailgun domain/messages",
- auth=("api", "mailgun api key"),
- data={"from": "Mailgun Sandbox <[email protected]>",
- "to": ["[email protected]", "[email protected]"],
- "subject": subject,
- "text": content,
- "html": "<html>It is so simple to send a message.<br/></html>"})
- 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@backup-online:# ' + cmd + '\n' + result
- content = 'SERVER IP : 127.0.0.1 \n'+'<br />'+'SERVER NAME : MyVPS \n'+'<br />'+'Project : MY TEST SERVER \n'+ '<br /><br />'
- result = result.split('\n')
- #print(result)
- 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('%')) > 90:
- subject = '[WARNING] SERVER FILESYSTEM USE% OVER ' + i + ', PLEASE CHECK!'
- content += ' '.join(line) + "\n <br />"
- if subject:
- send_mail(subject,content)
- #print(content)
- print('email sended')
- else:
- print('Everything is ok, keep on monitor.')
- if __name__ == '__main__':
- cmd = 'df -h'
- disk_check()
没有评论