python监控脚本

#!/usr/bin/env python
# -*- coding:utf8 -*-


import urllib
import datetime
import os
import re
import json
import sys
import logging
import Daemon
from providers.s_email import SendMailHandle
from providers.s_sms import SendsmsHandle
from providers.s_im import SendImHandle

default_encoding = 'utf-8'

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

with open('./cfg.json', 'r') as f:
    config = json.load(f)

data = config


class HTTPHandle(BaseHTTPRequestHandler):

    def transDicts(self, params, logger):
        dicts = {}
        if len(params) == 0:
            return
        params = params.split('&')
        for param in params:
            if 'tos' in param:
                dicts['tos'] = param.replace('tos=', '')
            if 'content' in param:
                dicts['content'] = param.replace('content=', '')
            if 'subject' in param:
                dicts['subject'] = param.replace('subject=', '')
            if 'type' in param:
                dicts['type'] = param.replace('type=', '')
        return dicts

    def do_POST(self):
        mpath, margs = urllib.splitquery(self.path)
        logging.config.fileConfig("./logging.ini")
        logger = logging.getLogger(__name__)
        logger.info("start to handle request")
        logger.info("self.path %s" % self.path)
        datas = self.rfile.read(int(self.headers['content-length']))
        logger.info("datas %s" % datas)
        datas = urllib.unquote(datas).decode("utf-8", 'ignore')  # 指定编码方式
        logger.info("datas %s" % datas)
        logger.info("data----=" + repr(datas))
        if not datas:
            request_data = self.transDicts(self.path.split("?")[1], logger)
            type_args = request_data.get("type")
        else:
            request_data = self.transDicts(datas, logger)
            type_args = margs.replace('type=', '')
            logger.info("request_data %s %s " % (type(request_data.get('content')), request_data.get('content')))

        logger.info("dict----:" + repr(request_data))
        pattern = r"(\[.*?\])"
        guid = re.findall(pattern, request_data.get('content'), re.M)
        content = ''
        if len(guid) > 2:
            dt = datetime.datetime.now()
            # try:
            t = guid[-1].replace('[', '').replace(']', '').split("+")
            dt = (" ").join(x for x in t[1:len(t)])
            # except BaseException,e:
            # logger.error("error:%s"%e)

            content = u'优先级:{0}\r\n状态:{1}\r\n监控对象:{2}\r\n日期:{3}\r\nMetric:{4}'.format(
                guid[0].replace('[', '').replace(']', ''),
                guid[1].replace('[', '').replace(']', ''),
                guid[2].replace('[', '').replace(']', ''),
                dt,
                request_data.get('content').split("[")[5].split("]")[0])

        if type_args == 'mail':
            mail_config = data.get('mail')
            try:
                mail_handle = SendMailHandle(mail_config.get('mail_host'), mail_config.get('mail_user'),
                                             mail_config.get('mail_pass'), mail_config.get('mail_postfix'))
                mail_handle.send(request_data.get('content'), request_data.get('tos'), request_data.get('subject'))
            except Exception as e:
                logger.info('ERROR: ' + repr(e))
        if type_args == 'sms':
            sms_config = data.get('sms')
            try:
                logger.info('data' + repr(request_data))
                sms_handle = SendsmsHandle(sms_config.get('api_url'))
                for phone in request_data.get('tos').split(','):
                    logger.info('phone:' + phone)
                    if phone:
                        sms_handle.send(phone, content if content else request_data.get('content'))
            except Exception as e:
                logger.info('ERROR: ' + repr(e))
        if type_args == 'im':
            im_config = data.get('im')
            try:
                im_handle = SendImHandle(im_config.get('api_email_url'), im_config.get('api_login_url'),
                                         im_config.get('api_send_url'), im_config.get('username'),
                                         im_config.get('password'), logger)
                im_handle.send(content if content else request_data.get('content'), request_data.get('tos'))
            except Exception as e:
                logger.info('ERROR: ' + repr(e))
        # request_data = json.loads(datas,encoding="utf-8")
        self.send_response(200)
        self.end_headers()
        logger.info("send successfully")


def port_to_pid(port):
    output = os.popen('lsof -i tcp:' + str(port))
    res = output.read()
    line = res.split("\n")
    if len(line) > 1:
        return line[1].split()[1]
    else:
        return 0


def kill_process(pid):
    if pid != 0:
        os.popen('kill -9 ' + pid)
    print "killed pid: " + pid


def main(argv):
    # with open('./cfg.json', 'r') as f:
    #     data = json.load(f)

    port = data["port"];

    if len(argv) > 1:
        action = argv[1]
    else:
        action = ""

    if action == "" or action == "start":
        pid = port_to_pid(port)
        if pid != 0:
            print "sms provider has started already, pid: " + pid
            return
        http_server = HTTPServer(('127.0.0.1', port), HTTPHandle)
        http_server.serve_forever()
    elif action == "stop":
        pid = port_to_pid(port)
        kill_process(pid)
    elif action == "restart":
        pid = port_to_pid(port)
        kill_process(pid)
        http_server = HTTPServer(('127.0.0.1', port), HTTPHandle)
        http_server.serve_forever()


class HttpServerDaemon(Daemon.Daemon):
    def _run(self):
        # with open('./cfg.json', 'r') as f:
        #     data = json.load(f)
        port = data["port"];
        http_server = HTTPServer(('0.0.0.0', port), HTTPHandle)
        self.logger.info('provider start runing')
        http_server.serve_forever()


if __name__ == '__main__':
    if sys.getdefaultencoding() != default_encoding:
        reload(sys)
        sys.setdefaultencoding(default_encoding)
    daemon = HttpServerDaemon("./var/smsprovider.pid")
    if len(sys.argv) > 1:
        action = sys.argv[1]
    else:
        action = ""

    if action == "" or action == "start":
        daemon.start()
    elif action == "stop":
        daemon.stop()
    elif action == "restart":
        daemon.restart()
    elif action == "status":
        print daemon.status()
    else:
        print "Unknown command"
        print "usage: %s start|stop|restart|status" % sys.argv[0]
        sys.exit(2)
sys.exit(0)

你可能感兴趣的:(python)