Python脚本email

2023-01-31 01:01:49 python email 脚本

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import re
import string
import os
import time
import Httplib
import urllib

import ConfigParser

import Mysqldb
from smtplib import SMTP

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
#from email.Header import Header
Python 2.3.*: email.Utils email.Encoders
from email.utils import COMMASPACE,fORMatdate
from email import encoders

#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]): 
    assert type(server) == dict 
    assert type(to) == list 
    assert type(files) == list 
 
    msg = MIMEMultipart() 
    msg['From'] = fro 
    msg['Subject'] = subject 
    msg['To'] = COMMASPACE.join(to) #COMMASPACE==', ' 
    msg['Date'] = formatdate(localtime=True) 
    msg["Accept-Language"]="zh-CN"
    msg["Accept-Charset"]="ISO-8859-1,utf-8"
    txt=MIMEText(text)
    txt.set_charset("utf-8")
    msg.attach(txt) 
 
    for file in files: 
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
        part.set_payload(open(file, 'rb'.read())) 
        encoders.encode_base64(part) 
        part.add_header('Content-Disposition', 'p_w_upload; filename="%s"' % os.path.basename(file)) 
        msg.attach(part) 
 
    #import smtplib 
    smtp = SMTP(server['name']) 
    smtp.login(server['user'], server['passwd']) 
    smtp.sendmail(fro, to, msg.as_string()) 
    smtp.close()


#tolist.split(',')
def send_sms(to,msg):
    '''
    send a sms
    '''
    if not to.isdigit():
        return
    if len(to) != 11:
        return

    params = urllib.urlencode({'mobiles':to, 'oauth_consumer_key': 'passport', 'oauth_signature': '(passprot-oauth-userkye%$&)2013-05-20publish','content':msg}) 
    headers = {"User-Agent" : "Mozilla/5.0 (windows NT 5.1) AppleWEBKit/537.36 (Khtml, like Gecko) Chrome/28.0.1500.95 Safari/537.36",
               "Content-type" : "application/x-www-form-urlencoded", 
               "Accept-Encoding" : "gzip,deflate,sdch",
               "Accept-Language" : "zh-CN,zh;q=0.8",
               "Accept" : "*/*"} 
    #http://sms.guagua.cn/sender/forthwith/smsess.do
    conn = httplib.HTTPConnection("sms.guagua.cn:80") 
    conn.request("POST", "/sender/forthwith/smsess.do", params, headers) 
    response = conn.getresponse()
    #print response.status, response.reason 
    #print response.msg
    #data = response.read()
    #print data
    conn.close()
    return {response.status:response.reason}


def read_ini():
    '''
    read db.ini file
    return list, length=5
    '''
    if not os.path.isfile('/usr/local/nagiOS/libexec/db.ini'):
        print ('db.ini not exsit!')
        return
    
    db_conf=[]

    cf = ConfigParser.ConfigParser()
    cf.read('/usr/local/nagios/libexec/db.ini')

    db_ip = cf.get('DB', 'ip')
    db_conf.append(db_ip)
    db_port = cf.getint('DB', 'port')
    db_conf.append(db_port)
    db_user = cf.get('DB', 'user')
    db_conf.append(db_user)
    db_pwd = cf.get('DB', 'pwd')
    db_conf.append(db_pwd)
    db_db = cf.get('DB', 'db')
    db_conf.append(db_db)

    return db_conf


def arg_parse(report_context):
    '''
    parse [COMM_MONITER:StatusLevel:serverType:serverid] by regex
    '''
    assert type(report_context) == list
    parselist = []
    pattern = re.compile(r'\[COMM_MONITER:(\d+):(\d+):(\d+)\](.*)')
    for line in report_context:
        match = pattern.findall(line)
        if match:
            parselist.append(match[0])

    return parselist

# OK 0
# WARNING 1
# CRITICAL 2
# UNKNOWN 3

def state_svr(state):
    ret = 3
    if 0 == cmp(state, 'OK'):
        ret = 0
    elif 0 == cmp(state, 'WARNING'):
        ret = 1
    elif 0 == cmp(state, 'CRITICAL'):
        ret = 2
    elif 0 == cmp(state, 'UNKNOWN'):
        ret = 3

    return ret
#"$HOSTALIAS$" 1 
#"$HOSTADDRESS$" 2
#"$LONGDATETIME$" 3
#"$SERVICESTATE$" 4
#"$SERVICEDESC$" 5
#"$SERVICEOUTPUT$$LONGSERVICEOUTPUT$" 6
#"$CONTACTEMAIL$" 7
#"$last_state_change$" 8
#"$sms$" 9 
#"$cmd$" 10 
def main():
    cur_pwd = os.getcwd()
    fp = open('/usr/local/nagios/libexec/mail.log','w')
    fp.write(cur_pwd+os.linesep)
    fp.write(str(len(sys.argv))+os.linesep)
    for a in sys.argv:
        fp.write(a+os.linesep)
    #fp.close()

    if len(sys.argv) < 11:
        fp.write('error sys.argv < 11!'+os.linesep)
        fp.close()
        return

    srv_ip = sys.argv[2]

    arg_tmp = sys.argv[6]+',cmd:'+sys.argv[10]
    fp.write(arg_tmp+os.linesep)
    srv_state = state_svr(sys.argv[4])

    mail = sys.argv[7]
    mail_addr = mail.split(',')

    last_state_chg = int(sys.argv[8])

    arg9 = sys.argv[9]
    mobilelist = arg9.split(',')

    mail_subject = sys.argv[1]+','+srv_ip+','+sys.argv[5]+','+sys.argv[4]
    #print arg_tmp
    svr_output = arg_tmp.split('\\n')
    
    # parse command line arg
    arg_list = arg_parse(svr_output)

    # read db.ini file
    db_conf = read_ini()
    if not db_conf:
        fp.write('read db.ini failed!'+os.linesep)
        fp.close()
        return
    fp.write('read db.ini suss!'+os.linesep)
    # connect mysql server
    conn = Mysqldb.Connection(host=db_conf[0], port=db_conf[1],user=db_conf[2], passwd=db_conf[3], db=db_conf[4])
    if not conn.open:
        fp.write('mysql connect failed!'+os.linesep)
        fp.close()
        return
    conn.select_db(db_conf[4])
    cur = conn.cursor()
    fp.write('mysql connect ret = '+str(conn.open)+os.linesep)
    # set charset = utf8
    cur.execute("SET NAMES utf8")
    #cur.execute("SET CHARACTER_SET_CLIENT=utf8")
    #cur.execute("SET CHARACTER_SET_RESULTS=utf8")
    conn.commit()

    # get current time
    cur_time = time.time()*1000
    g_server = {'name':'mail.17guagua.com','user':'ggmonitor@17guagua.com','passwd':r'\b=DS/7H'}
    g_fro     = 'ggmonitor@17guagua.com'

    g_subject = '联通'+mail_subject
    fp.write(g_subject+os.linesep)
    if len(arg_list) == 0:
        alarm_desc = arg_tmp.decode('utf-8').encode('utf-8') 
        t_server_alarm_log = "INSERT INTO t_service_alarm_log(service_id,server_type,service_ip,alarm_type,alarm_desc,alarm_time,store_time,last_state_change) \
        VALUES (%d,%d,'%s',%d,'%s',%d,%d,%d)" % (0,0,srv_ip,srv_state,alarm_desc,cur_time,cur_time,last_state_chg)
        cur.execute(t_server_alarm_log)
        fp.write('insert t_service_alarm_log suss!\n')
        # commit insert op
        conn.commit()
        
        # send warning mail
        send_mail(g_server,g_fro,mail_addr,g_subject,alarm_desc)        
        fp.write('sendmail suss!\n')
    # insert t_server_alarm_log
    for arg in arg_list:
        #fp.write('arg='+arg+',')
        alarm_type = int(arg[0])
        service_type = int(arg[1])
        service_id = int(arg[2])
        alarm_desc = '联通机房检测到异常:\n' + arg[3].decode('utf-8').encode('utf-8')
        
        t_server_alarm_log = "INSERT INTO t_service_alarm_log(service_id,server_type,service_ip,alarm_type,alarm_desc,alarm_time,store_time) \
        VALUES (%d,%d,'%s',%d,'%s',%d,%d)" % (service_id,service_type,srv_ip,alarm_type,alarm_desc,cur_time,cur_time)
        cur.execute(t_server_alarm_log)
        fp.write('insert t_service_alarm_log suss!\n')
        # commit insert op
        conn.commit()

        # send warning mail
        send_mail(g_server,g_fro,mail_addr,g_subject,alarm_desc)        
        fp.write('send_mail suss!\n')
    # close mysql server
    cur.close()
    conn.close()

    # send sms
    for mobile in mobilelist:
        msg_list = [mobile,g_subject]
        msg = ','.join(msg_list)
        send_sms(mobile,msg)

    fp.write('send sms suss!\n')
    fp.close()

if __name__ == '__main__':
    main()

相关文章