专栏首页python3Python脚本email

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()

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Python创建简单的HTTP服务

      python -m SimpleHTTPServer 80  # 默认端口是8000,目录是当前目录

    py3study
  • Python使用ldap3操作微软AD

    对于client连接ldap server的策略,ldap3提供了4种选择,可以通过client_strategy设置Connection object应用哪种...

    py3study
  • Python爬虫基础--分布式爬取贝壳网

    py3study
  • Ubuntu下各个目录的一般作用

    /  这就是根目录,一台电脑有且只有一个根目录,所有的文件都是从这里开始的。举个例子:当你在终端里输入“/home”,你其实是在告诉电脑,先从/(根目录)...

    闵开慧
  • 数据分析要会写代码

    最近工作任务有些忙,主要是各个部门的数据分析需求再加上APP后端性能优化挤到一块儿去了。

    有福
  • SignalR QuickStart

    SignalR 是一个集成的客户端与服务器库,基于浏览器的客户端和基于 ASP.NET 的服务器组件可以借助它来进行双向多步对话。 换句话说,该对话可不受限制地...

    张善友
  • SignalR QuickStart

    SignalR 是一个集成的客户端与服务器库,基于浏览器的客户端和基于 ASP.NET 的服务器组件可以借助它来进行双向多步对话。 换句话说,该对话可不受限制地...

    莫问今朝
  • 从数据库创建深入学习Oracle技术:那些年 mkplug 偷偷执行的Plugin操作

    在很多Oracle文档中,可能大家都注意过Oracle用来进行测试的一个表空间,这个表空间中有一系列预置的用户和数据,可以用于数据库或BI的很多测试实验。 这个...

    数据和云
  • 【奥斯卡理财星体系 第四章】丨你该如何选择适合的理财工具

    在我们学习了理财“心法”,认识了“自己”,并且对自己适合的收益预期,也有了明确概念之后,接下去就到了童鞋们期盼已久的,学习理财“招式”的时间啦。

    Hongten
  • 一文多图搞懂数据结构的双链表!

    前面讲过线性表中[顺序表和链表].但双向链表无论在考察还是运用中都占有很大的比例,笔者旨在通过本文与读者一起学习分享双链表相关知识。

    bigsai

扫码关注云+社区

领取腾讯云代金券