Пример #1
0
def append_log(string,level=1):
    global logfile
    global loglevel
    global uniq_id

    try:
        string = "[%f] %s" % (uniq_id,str(string),)
    except:
        string = "[%f] %s" % (uniq_id,string,)

    from karesansui.lib.collectd.utils import append_line
    if loglevel & level:
        append_line(logfile,string)
Пример #2
0
def write_log(string,priority="WARNING"):

    priorities = [
              "DEBUG",
              "INFO",
              "OKAY",
              "WARNING",
              "FAILURE",
              ]

    rotate_log()

    # ログの書き込み
    msg = "%s [%s] %s" % (time.strftime(COLLECTD_ALERT_LOG_TIMESTAMP_FORMAT,time.localtime(time.time())),priority,string,)
    append_line(COLLECTD_ALERT_LOG,msg)

    return
Пример #3
0
def append_log(string, level=1):
    global logfile
    global loglevel
    global uniq_id

    try:
        string = "[%f] %s" % (
            uniq_id,
            str(string),
        )
    except:
        string = "[%f] %s" % (
            uniq_id,
            string,
        )

    from karesansui.lib.collectd.utils import append_line
    if loglevel & level:
        append_line(logfile, string)
Пример #4
0
def write_log(string, priority="WARNING"):

    priorities = [
        "DEBUG",
        "INFO",
        "OKAY",
        "WARNING",
        "FAILURE",
    ]

    rotate_log()

    # ログの書き込み
    msg = "%s [%s] %s" % (
        time.strftime(COLLECTD_ALERT_LOG_TIMESTAMP_FORMAT,
                      time.localtime(time.time())),
        priority,
        string,
    )
    append_line(COLLECTD_ALERT_LOG, msg)

    return
Пример #5
0
def exec_script(script="",user="******",msg="",watch_name="",logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile,"[%s] Entering function '%s'." % (func_name,func_name,))

    # スクリプトの一時保存ディレクトリを作成
    SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR,)
    if not os.path.exists(SCRIPT_TMP_DIR):
        os.makedirs(SCRIPT_TMP_DIR)
        r_chmod(SCRIPT_TMP_DIR,0770)
        r_chown(SCRIPT_TMP_DIR,KARESANSUI_USER)
        r_chgrp(SCRIPT_TMP_DIR,KARESANSUI_GROUP)
        append_line(logfile,"[%s] Create directory '%s'." % (func_name,SCRIPT_TMP_DIR,))

    try:
       user_id = int(user)
    except:
       user_id = pwd.getpwnam(user)[2]

    # スクリプトファイルの生成
    fname = None
    try:
        fd, fname  = tempfile.mkstemp(suffix="",prefix="script_",dir=SCRIPT_TMP_DIR)
        append_line(logfile,"[%s] Create script '%s'." % (func_name,fname,))
        fp = os.fdopen(fd,"w")
        fcntl.lockf(fp.fileno(), fcntl.LOCK_EX)
        script = re.sub("%{watch_name}",watch_name.encode('utf_8'),script)
        script = re.sub("%{msg}"       ,msg.encode('utf_8')       ,script)
        fp.write(script)
        fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)
        fp.close()
        os.chmod(fname,0700)
        os.chown(fname,user_id,-1)

    except:
        append_line(logfile,"[%s] Error: failed to create script." % (func_name,))
        if fname is not None and os.path.exists(fname):
            os.unlink(fname)

    if fname is not None and os.path.exists(fname):

        # マジッククッキーを調べる
        magic_cookie = open(fname).readline().rstrip()
        if magic_cookie[-8:] == "bin/perl":
            interpreter = "perl"
        elif magic_cookie[-10:] == "bin/python" or \
             magic_cookie[-10:] == "env python":
            interpreter = "python"
        elif magic_cookie[-7:] == "bin/php":
            interpreter = "php"
        elif magic_cookie[-8:] == "bin/ruby":
            interpreter = "ruby"
        elif magic_cookie[-8:] == "bin/tcsh":
            interpreter = "tcsh"
        elif magic_cookie[-7:] == "bin/csh":
            interpreter = "csh"
        else:
            interpreter = "sh"

        # コマンド文字列の作成
        if os.getuid() != user_id:
            command_args = ["su","-s", "/bin/bash", user, fname]
        else:
            command_args = [interpreter,fname]

        # コマンドの実行
        append_line(logfile,"[%s] Execute command '%s'." % (func_name," ".join(command_args),))
        (rc,res) = execute_command(command_args)
        new_res = []
        for _aline in res:
            append_line(logfile,"[%s] output> %s" % (func_name,_aline,))
            _aline = re.sub("^%s:[ \t]+" % fname, "", _aline)
            new_res.append(_aline)
            pass
        append_line(logfile,"[%s] command return value = %d" % (func_name,rc,))

        os.unlink(fname)

        retval = [rc,new_res]
    else:
        append_line(logfile,"[%s] Error: cannot create script file." % (func_name,))

    append_line(logfile,"[%s] Leaving function '%s'." % (func_name,func_name,))
    return retval
Пример #6
0
def exec_script(script="",
                user="******",
                msg="",
                watch_name="",
                logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile, "[%s] Entering function '%s'." % (
        func_name,
        func_name,
    ))

    # スクリプトの一時保存ディレクトリを作成
    SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR, )
    if not os.path.exists(SCRIPT_TMP_DIR):
        os.makedirs(SCRIPT_TMP_DIR)
        r_chmod(SCRIPT_TMP_DIR, 0770)
        r_chown(SCRIPT_TMP_DIR, KARESANSUI_USER)
        r_chgrp(SCRIPT_TMP_DIR, KARESANSUI_GROUP)
        append_line(
            logfile, "[%s] Create directory '%s'." % (
                func_name,
                SCRIPT_TMP_DIR,
            ))

    try:
        user_id = int(user)
    except:
        user_id = pwd.getpwnam(user)[2]

    # スクリプトファイルの生成
    fname = None
    try:
        fd, fname = tempfile.mkstemp(suffix="",
                                     prefix="script_",
                                     dir=SCRIPT_TMP_DIR)
        append_line(logfile, "[%s] Create script '%s'." % (
            func_name,
            fname,
        ))
        fp = os.fdopen(fd, "w")
        fcntl.lockf(fp.fileno(), fcntl.LOCK_EX)
        script = re.sub("%{watch_name}", watch_name.encode('utf_8'), script)
        script = re.sub("%{msg}", msg.encode('utf_8'), script)
        fp.write(script)
        fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)
        fp.close()
        os.chmod(fname, 0700)
        os.chown(fname, user_id, -1)

    except:
        append_line(logfile,
                    "[%s] Error: failed to create script." % (func_name, ))
        if fname is not None and os.path.exists(fname):
            os.unlink(fname)

    if fname is not None and os.path.exists(fname):

        # マジッククッキーを調べる
        magic_cookie = open(fname).readline().rstrip()
        if magic_cookie[-8:] == "bin/perl":
            interpreter = "perl"
        elif magic_cookie[-10:] == "bin/python" or \
             magic_cookie[-10:] == "env python":
            interpreter = "python"
        elif magic_cookie[-7:] == "bin/php":
            interpreter = "php"
        elif magic_cookie[-8:] == "bin/ruby":
            interpreter = "ruby"
        elif magic_cookie[-8:] == "bin/tcsh":
            interpreter = "tcsh"
        elif magic_cookie[-7:] == "bin/csh":
            interpreter = "csh"
        else:
            interpreter = "sh"

        # コマンド文字列の作成
        if os.getuid() != user_id:
            command_args = ["su", "-s", "/bin/bash", user, fname]
        else:
            command_args = [interpreter, fname]

        # コマンドの実行
        append_line(
            logfile, "[%s] Execute command '%s'." % (
                func_name,
                " ".join(command_args),
            ))
        (rc, res) = execute_command(command_args)
        new_res = []
        for _aline in res:
            append_line(logfile, "[%s] output> %s" % (
                func_name,
                _aline,
            ))
            _aline = re.sub("^%s:[ \t]+" % fname, "", _aline)
            new_res.append(_aline)
            pass
        append_line(logfile, "[%s] command return value = %d" % (
            func_name,
            rc,
        ))

        os.unlink(fname)

        retval = [rc, new_res]
    else:
        append_line(logfile,
                    "[%s] Error: cannot create script file." % (func_name, ))

    append_line(logfile, "[%s] Leaving function '%s'." % (
        func_name,
        func_name,
    ))
    return retval
Пример #7
0
def send_mail(recipient=None, sender=None, server="localhost", port=25, message="", extra_message="", watch_name="", logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile,"[%s] Entering function '%s'." % (func_name,func_name,))

    smtp_server = server.split(":")[0]
    try:
        smtp_port = int(port)
    except:
        smtp_port = 25

    try:
        socket_timeout
    except:
        socket_timeout = 30

    if recipient is not None:

        append_line(logfile,"[%s] Connecting SMTP server" % (func_name,))
        append_line(logfile,"[%s] smtp_server :%s" % (func_name,smtp_server,))
        append_line(logfile,"[%s] smtp_port   :%s" % (func_name,smtp_port,))

        mail = MAIL_LIB(smtp_server,smtp_port)

        if socket_timeout is None:
            socket_timeout = 30
        mail.set_timeout(int(socket_timeout))

        mail.set_verbosity(0)

        if sender is None:
            mail.set_sender(DEFAULT_SENDER)
        else:
            mail.set_sender(sender)

        mail.encoding   = "utf-8"

        mail.set_recipients(recipient.split(","))
        append_line(logfile,"[%s] recipient   :%s" % (func_name,recipient,))

        # デフォルトのヘッダをセット
        headers = {}
        headers['Subject'] = re.sub("\%\{watch_name\}",watch_name,DEFAULT_SUBJECT)

        # カテゴリ用のヘッダとボディを上書きでセット
        rawbody = ""
        try:
            append_line(logfile,"[%s] message   :%s" % (func_name,message,))
            try:
                del headers["Content-Transfer-Encoding"]
                message = message.encode('utf-8')
                message = str(message)
            except:
                pass
            append_line(logfile,"[%s] lang %s" % (func_name,os.environ['LANG']))
            extra_args = {"message":message}
            eml = emlParser().read_conf(extra_args=extra_args)
            parse_ret = preprint_r(eml,return_var=True)
            append_line(logfile,"[%s] parse_ret   :%s" % (func_name,parse_ret,))

            header  = eml['@message']['value']['header']['value']
            rawbody += eml['@message']['value']['rawbody']['value']
            for _k,_v in header.iteritems():
                headers[_k] = _v['value']
        except:
            pass
        try:
            extra_message = extra_message.encode('utf-8')
        except:
            pass
        rawbody += "\n\n" + extra_message

        # Add footer
        rawbody += "\n\n" + "(brought to you by %s)" % AppName

        append_line(logfile,"[%s] rawbody   :%s" % (func_name,rawbody,))

        mail.set_body(rawbody)

        # 一旦メッセージを生成
        mail.create_message()

        #preprint_r(mail.msg._headers)
        for _k,_v in headers.iteritems():
            append_line(logfile,"[%s] Headers %-12s: %s" % (func_name,_k,_v))
            try:
                del mail.msg[_k]
            except:
                pass
            if _k == "Subject":
                try:
                    mail.set_subject(_v.encode('utf_8'))
                except:
                    mail.set_subject(_v)
            else:
                mail.msg[_k] = _v

        try:
            del mail.msg["Content-Transfer-Encoding"]
            mail.msg["Content-Transfer-Encoding"] = "base64"
        except:
            pass

        for _header in mail.msg._headers:
            append_line(logfile,"[%s] Header %-12s: %s" % (func_name,_header[0],_header[1]))
        #sys.exit()

        try:
            mail.send()
            retval = True
        except MAIL_LIB_Exception, msg:
            append_line(logfile,"[%s] Error: %s" % (func_name,str(msg),))
        except Exception:
            append_line(logfile,"[%s] Error: failed to send mail." % (func_name,))
Пример #8
0
            pass

        for _header in mail.msg._headers:
            append_line(logfile,"[%s] Header %-12s: %s" % (func_name,_header[0],_header[1]))
        #sys.exit()

        try:
            mail.send()
            retval = True
        except MAIL_LIB_Exception, msg:
            append_line(logfile,"[%s] Error: %s" % (func_name,str(msg),))
        except Exception:
            append_line(logfile,"[%s] Error: failed to send mail." % (func_name,))

    else:
        append_line(logfile,"[%s] Error: recipient is not set." % (func_name,))

    append_line(logfile,"[%s] Leaving function '%s'." % (func_name,func_name,))
    return retval

if __name__ == '__main__':
    """Testing
    """
    recipient = "taizo@localhost"
    recipient = "root@localhost"
    sender    = None
    server = "localhost"
    logfile = "/dev/stdout"
    watch_name = u'\u30e1\u30e2\u30ea\u4f7f\u7528\u91cf\u3067\u3059'

    message = """Message-ID: <*****@*****.**>
Пример #9
0
def send_mail(recipient=None,
              sender=None,
              server="localhost",
              port=25,
              message="",
              extra_message="",
              watch_name="",
              logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile, "[%s] Entering function '%s'." % (
        func_name,
        func_name,
    ))

    smtp_server = server.split(":")[0]
    try:
        smtp_port = int(port)
    except:
        smtp_port = 25

    try:
        socket_timeout
    except:
        socket_timeout = 30

    if recipient is not None:

        append_line(logfile, "[%s] Connecting SMTP server" % (func_name, ))
        append_line(logfile, "[%s] smtp_server :%s" % (
            func_name,
            smtp_server,
        ))
        append_line(logfile, "[%s] smtp_port   :%s" % (
            func_name,
            smtp_port,
        ))

        mail = MAIL_LIB(smtp_server, smtp_port)

        if socket_timeout is None:
            socket_timeout = 30
        mail.set_timeout(int(socket_timeout))

        mail.set_verbosity(0)

        if sender is None:
            mail.set_sender(DEFAULT_SENDER)
        else:
            mail.set_sender(sender)

        mail.encoding = "utf-8"

        mail.set_recipients(recipient.split(","))
        append_line(logfile, "[%s] recipient   :%s" % (
            func_name,
            recipient,
        ))

        # デフォルトのヘッダをセット
        headers = {}
        headers['Subject'] = re.sub("\%\{watch_name\}", watch_name,
                                    DEFAULT_SUBJECT)

        # カテゴリ用のヘッダとボディを上書きでセット
        rawbody = ""
        try:
            append_line(logfile, "[%s] message   :%s" % (
                func_name,
                message,
            ))
            try:
                del headers["Content-Transfer-Encoding"]
                message = message.encode('utf-8')
                message = str(message)
            except:
                pass
            append_line(logfile,
                        "[%s] lang %s" % (func_name, os.environ['LANG']))
            extra_args = {"message": message}
            eml = emlParser().read_conf(extra_args=extra_args)
            parse_ret = preprint_r(eml, return_var=True)
            append_line(logfile, "[%s] parse_ret   :%s" % (
                func_name,
                parse_ret,
            ))

            header = eml['@message']['value']['header']['value']
            rawbody += eml['@message']['value']['rawbody']['value']
            for _k, _v in header.iteritems():
                headers[_k] = _v['value']
        except:
            pass
        try:
            extra_message = extra_message.encode('utf-8')
        except:
            pass
        rawbody += "\n\n" + extra_message

        # Add footer
        rawbody += "\n\n" + "(brought to you by %s)" % AppName

        append_line(logfile, "[%s] rawbody   :%s" % (
            func_name,
            rawbody,
        ))

        mail.set_body(rawbody)

        # 一旦メッセージを生成
        mail.create_message()

        #preprint_r(mail.msg._headers)
        for _k, _v in headers.iteritems():
            append_line(logfile,
                        "[%s] Headers %-12s: %s" % (func_name, _k, _v))
            try:
                del mail.msg[_k]
            except:
                pass
            if _k == "Subject":
                try:
                    mail.set_subject(_v.encode('utf_8'))
                except:
                    mail.set_subject(_v)
            else:
                mail.msg[_k] = _v

        try:
            del mail.msg["Content-Transfer-Encoding"]
            mail.msg["Content-Transfer-Encoding"] = "base64"
        except:
            pass

        for _header in mail.msg._headers:
            append_line(
                logfile,
                "[%s] Header %-12s: %s" % (func_name, _header[0], _header[1]))
        #sys.exit()

        try:
            mail.send()
            retval = True
        except MAIL_LIB_Exception, msg:
            append_line(logfile, "[%s] Error: %s" % (
                func_name,
                str(msg),
            ))
        except Exception:
            append_line(logfile,
                        "[%s] Error: failed to send mail." % (func_name, ))
Пример #10
0
        #sys.exit()

        try:
            mail.send()
            retval = True
        except MAIL_LIB_Exception, msg:
            append_line(logfile, "[%s] Error: %s" % (
                func_name,
                str(msg),
            ))
        except Exception:
            append_line(logfile,
                        "[%s] Error: failed to send mail." % (func_name, ))

    else:
        append_line(logfile,
                    "[%s] Error: recipient is not set." % (func_name, ))

    append_line(logfile, "[%s] Leaving function '%s'." % (
        func_name,
        func_name,
    ))
    return retval


if __name__ == '__main__':
    """Testing
    """
    recipient = "taizo@localhost"
    recipient = "root@localhost"
    sender = None
    server = "localhost"