def post(self, *args, **kwargs):
        ### 发送邮件
        data = json.loads(self.request.body.decode('utf-8'))
        to_list = data.get('to_list', None)
        subject = data.get('subject', None)
        content = data.get('content', None)
        subtype = data.get('subtype', None)
        att = data.get('att', None)
        redis_conn = cache_conn()
        if not to_list and not subject and not content:
            return self.write(dict(code=-1, msg='收件人、邮件标题、邮件内容不能为空'))

        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        try:
            obj = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

            obj.send_mail(to_list, subject, content, subtype=subtype, att=att)
            return self.write(dict(code=0, msg='邮件发送成功'))

        except Exception as e:
            return self.write(dict(code=-1, msg='邮件发送失败 {}'.format(str(e))))
Пример #2
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode('utf-8'))
        check_key = data.get('check_key')
        user_id = self.get_current_id()

        redis_conn = cache_conn()
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)

        if check_key == 'EMAIL':
            with DBContext('r') as session:
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

            obj = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
                mail_tls=True
                if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

            obj.send_mail(mail_to[0], 'OPS测试邮件', '测试发送邮件成功', subtype='plain')
            return self.write(dict(code=0, msg='测试邮件已经发送'))

        elif check_key == 'SMS':
            obj = SendSms(config_info.get(const.SMS_REGION),
                          config_info.get(const.SMS_DOMAIN),
                          config_info.get(const.SMS_PRODUCT_NAME),
                          config_info.get(const.SMS_ACCESS_KEY_ID),
                          config_info.get(const.SMS_ACCESS_KEY_SECRET))

            query_response = obj.query_send_detail(
                '', '11111111111', 1, 1,
                time.strftime("%Y%m%d", time.localtime()))
            query_response = json.loads(query_response.decode('utf-8'))
            if query_response.get("Message") == "OK":
                return self.write(dict(code=0, msg='测试短信成功'))
            else:
                return self.write(
                    dict(code=-2, msg='测试短信失败{}'.format(str(query_response))))
        elif check_key == 'LDAP':
            ldap_ssl = True if config_info.get(
                const.LDAP_USE_SSL) == '1' else False

            obj = LdapApi(config_info.get(const.LDAP_SERVER_HOST),
                          config_info.get(const.LDAP_ADMIN_DN),
                          config_info.get(const.LDAP_ADMIN_PASSWORD),
                          int(config_info.get(const.LDAP_SERVER_PORT, 389)),
                          ldap_ssl)

            if obj.ldap_server_test():
                return self.write(dict(code=0, msg='LDAP连接测试成功'))
            else:
                return self.write(dict(code=-1, msg='LDAP连接测试不成功,请仔细检查配置'))

        else:
            return self.write(dict(code=-1, msg='未知测试项目'))
Пример #3
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        alerts = data.get('alerts')  # 获取AlertManager POST报警数据
        #alerts = [{'status': 'firing', 'labels': {'alertname': 'Node主机CPU利用率过高', 'instance': '172.16.1.53:9100', 'prometheus': 'monitoring/k8s', 'severity': '严重'}, 'annotations': {'detail': '172.16.1.53:9100: CPU利用率过高于75% (当前值: 92.11666666667345)', 'summary': '172.16.1.53:9100: CPU利用率过高'}, 'startsAt': '2019-03-18T05:34:54.025953211Z', 'endsAt': '0001-01-01T00:00:00Z', 'generatorURL': 'http://prometheus-k8s-1:9090/graph?g0.expr=100+-+%28avg+by%28instance%29+%28irate%28node_cpu_seconds_total%7Bjob%3D%22node-exporter%22%2Cmode%3D%22idle%22%7D%5B5m%5D%29%29+%2A+100%29+%3E+75&g0.tab=1'}]
        for alerts_data in alerts:
            labels = alerts_data.get('labels')
            alert_name = labels.get('alertname')
            print('alert_name---->', alert_name)
            cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
            if cache_config_info:
                config_info = convert(cache_config_info)
            else:
                config_info = configs['email_info']

            emails_list = redis_conn.hvals(alert_name)
            print('Email_list----->', emails_list)
            sm = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
            ### 如果没有redis没有配置
            if not emails_list:
                # print(configs.get('default_email'))[0]  #元祖类型
                sm.send_mail(
                    configs.get('default_email')[0], alert_name,
                    alerts_data['annotations']['detail'])
                # print('msg=',alerts_data['annotations']['detail'])
                return self.write(dict(code=-1, msg="没有匹配到规则"))

            ### 默认发送邮件
            sm.send_mail(",".join(emails_list), alert_name,
                         alerts_data['annotations']['detail'])

            # 严重警告发短信
            if labels.get('severity') == "严重":
                if not configs.get('sign_name') or not configs.get(
                        'template_code'):
                    sm.send_mail(configs.get('default_email'), alert_name,
                                 '请配置短信的sign_name和template_code')
                else:
                    phone_numbers = redis_conn.hkeys(alert_name)
                    # 发送内容
                    params = {"msg": alerts_data['annotations']['detail']}
                    sms = SendSms(config_info.get(const.SMS_REGION),
                                  config_info.get(const.SMS_DOMAIN),
                                  config_info.get(const.SMS_PRODUCT_NAME),
                                  config_info.get(const.SMS_ACCESS_KEY_ID),
                                  config_info.get(const.SMS_ACCESS_KEY_SECRET))

                    sms.send_sms(phone_numbers=",".join(phone_numbers),
                                 template_param=params,
                                 sign_name=configs.get('sign_name')[0],
                                 template_code=configs.get('template_code')[0])

        return self.write(dict(code=0, msg="发送成功", data=alerts))
Пример #4
0
    def send_mail_pool(self, *args_list):
        send_list = args_list[0]
        config_info = args_list[1]
        try:
            obj = SendMail(mail_host=config_info.get(const.EMAIL_HOST),
                           mail_port=config_info.get(const.EMAIL_PORT),
                           mail_user=config_info.get(const.EMAIL_HOST_USER),
                           mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                           mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
                           mail_tls=True if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

            obj.send_mail(send_list[0], send_list[1], send_list[2], subtype=send_list[3], att=send_list[4])
            return dict(code=0, msg='邮件发送成功')

        except Exception as e:
            return dict(code=-1, msg='邮件发送失败 {}'.format(str(e)))
Пример #5
0
 def send_mail(self, content):
     """
     发送Mail
     :return:
     content: 邮件内容
     """
     cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
     if cache_config_info:
         config_info = convert(cache_config_info)
     else:
         config_info = configs['email_info']
     sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                   mail_user=config_info.get(const.EMAIL_HOST_USER),
                   mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                   mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
     sm.send_mail(AWS_EVENT_TO_EMAIL, 'AwsEvents告警', content)
Пример #6
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) != 1:
            return self.write(dict(code=-2, msg='一次只能选择一个用户,且不能为空'))

        user_id = user_list[0]
        with DBContext('r') as session:
            user_info = session.query(Users).filter(
                Users.user_id == user_id).first()

        ### 生成token
        if user_info.superuser == '0':
            is_superuser = True
        else:
            is_superuser = False

        token_info = dict(user_id=user_id,
                          username=user_info.username,
                          nickname=user_info.nickname,
                          is_superuser=is_superuser,
                          exp_time=1100)
        auth_token = AuthToken()
        auth_key = auth_token.encode_auth_token_v2(**token_info)
        if isinstance(auth_key, bytes): auth_key = auth_key.decode()

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            mail_to = session.query(Users.email).filter(
                Users.user_id == self.get_current_id()).first()

        if mail_to[0] == user_info.email:
            obj.send_mail(mail_to[0], '令牌,有效期三年', auth_key, subtype='plain')
        else:
            obj.send_mail(mail_to[0], '令牌,有效期三年', auth_key, subtype='plain')
            obj.send_mail(user_info.email,
                          '令牌,有效期三年',
                          auth_key,
                          subtype='plain')
        return self.write(dict(code=0, msg='Token已经发送到邮箱', data=auth_key))
Пример #7
0
    def send_email(self, alert_email_list, content):
        """
        发送邮件
        :return:
        """

        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
        if cache_config_info:
            config_info = convert(cache_config_info)
        else:
            config_info = configs['email_info']

        # emails_list = redis_conn.hvals(alert_name)
        sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                      mail_user=config_info.get(const.EMAIL_HOST_USER),
                      mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                      mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
        ### 默认发送邮件
        sm.send_mail(",".join(alert_email_list), 'DevOps消息提醒', content)
Пример #8
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) < 1:
            return self.write(dict(code=-1, msg='用户不能为空'))

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            for user_id in user_list:
                mfa = base64.b32encode(
                    bytes(str(shortuuid.uuid() + shortuuid.uuid())[:-9],
                          encoding="utf-8")).decode("utf-8")
                session.query(Users).filter(Users.user_id == user_id).update({
                    Users.last_ip:
                    '',
                    Users.google_key:
                    mfa
                })
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

                obj.send_mail(mail_to[0], '重置MFA', mfa, subtype='plain')

        return self.write(dict(code=0, msg='重置MFA成功,新的MFA已经发送到邮箱'))
Пример #9
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) < 1:
            return self.write(dict(code=-2, msg='用户不能为空'))

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            for user_id in user_list:
                md5_password = shortuuid.uuid()
                new_password = gen_md5(md5_password)
                session.query(Users).filter(Users.user_id == user_id).update(
                    {Users.password: new_password})
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

                obj.send_mail(mail_to[0],
                              '修改密码',
                              md5_password,
                              subtype='plain')
        return self.write(dict(code=0, msg='重置密码成功,新密码已经发送到邮箱'))
Пример #10
0
def check_reminder():
    """
    用途:
        检查哪些事件需要进行邮件提醒
    逻辑:
        这里逻辑简单说明下如下:
        01. 先获取到所有事件的到期时间
        02. 获取所有事件中每条事件都需要提前多少天进行提醒
        03. 计算从哪天开始进行提醒(过期时间 - 提前提醒天数 = 开始提醒的日期)
        04. 计算出来的·开始提醒日期· <= 现在时间 都进行报警
    :return:
    """
    # 邮箱配置信息
    config_info = redis_conn.hgetall(const.APP_SETTINGS)
    sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST),
                  mail_port=config_info.get(const.EMAIL_PORT),
                  mail_user=config_info.get(const.EMAIL_HOST_USER),
                  mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                  mail_ssl=True
                  if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

    for msg in db_session.query(PaidMG).all():
        if msg.paid_end_time < datetime.datetime.now():
            email_content = '{}已过期,请删除该提醒'.format(msg.paid_name)
            exp_paid_name = msg.paid_name
            emails_list = redis_conn.hvals(msg.paid_name)
            sm.send_mail(",".join(emails_list), '运维提醒信息', email_content)
        reminder_time = msg.paid_end_time - datetime.timedelta(
            days=int(msg.reminder_day))
        if reminder_time <= datetime.datetime.now():
            if msg.paid_name != exp_paid_name:
                remainder_time = msg.paid_end_time - datetime.datetime.now()
                email_content = ('{}还有{}天到期,请留意'.format(
                    msg.paid_name, remainder_time.days))
                emails_list = redis_conn.hvals(msg.paid_name)
                sm.send_mail(",".join(emails_list), '运维提醒信息', email_content)
Пример #11
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        username = data.get('username', None)
        nickname = data.get('nickname', None)
        password = data.get('password', None)
        department = data.get('department', None)
        tel = data.get('tel', None)
        wechat = data.get('wechat', None)
        no = data.get('no', None)
        email = data.get('email', None)
        if not username or not nickname or not department or not tel or not wechat or not no or not email:
            return self.write(dict(code=-1, msg='参数不能为空'))

        with DBContext('r') as session:
            user_info1 = session.query(Users).filter(
                Users.username == username).first()
            user_info2 = session.query(Users).filter(Users.tel == tel).first()
            user_info3 = session.query(Users).filter(
                Users.email == email).first()
            user_info4 = session.query(Users).filter(
                Users.nickname == nickname).first()

        if user_info1:
            return self.write(dict(code=-2, msg='用户名已注册'))

        if user_info2:
            return self.write(dict(code=-3, msg='手机号已注册'))

        if user_info3:
            return self.write(dict(code=-4, msg='邮箱已注册'))

        if user_info4:
            return self.write(dict(code=-4, msg='昵称已注册'))

        if not password:
            md5_password = shortuuid.uuid()
            password = gen_md5(md5_password)
        else:
            if not check_password(password):
                return self.write(
                    dict(code=-5, msg='密码复杂度必须为: 超过8位,包含数字,大小写字母 等'))
            password = gen_md5(password)

        mfa = base64.b32encode(
            bytes(str(shortuuid.uuid() + shortuuid.uuid())[:-9],
                  encoding="utf-8")).decode("utf-8")

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            session.add(
                Users(username=username,
                      password=password,
                      nickname=nickname,
                      department=department,
                      tel=tel,
                      wechat=wechat,
                      no=no,
                      email=email,
                      google_key=mfa,
                      superuser='******'))

        obj.send_mail(email,
                      '用户注册成功',
                      '密码为:{} \n MFA:{}'.format(password, mfa),
                      subtype='plain')
        return self.write(
            dict(code=0, msg='恭喜你! 注册成功,赶紧联系管理员给你添加权限吧!!!', mfa=mfa))
Пример #12
0
def check_reminder():
    """
    用途:
        检查哪些事件需要进行邮件提醒
    逻辑:
        这里逻辑简单说明下如下:
        01. 先获取到所有事件的到期时间
        02. 获取所有事件中每条事件都需要提前多少天进行提醒
        03. 计算从哪天开始进行提醒(过期时间 - 提前提醒天数 = 开始提醒的日期)
        04. 计算出来的·开始提醒日期· <= 现在时间 都进行报警
    :return:
    """
    # 邮箱配置信息
    config_info = redis_conn.hgetall(const.APP_SETTINGS)
    sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                  mail_user=config_info.get(const.EMAIL_HOST_USER),
                  mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                  mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

    for msg in db_session.query(PaidMG).all():
        reminder_time = msg.paid_end_time - datetime.timedelta(days=int(msg.reminder_day))
        if reminder_time <= datetime.datetime.now():
            emails_list = redis_conn.hvals(msg.paid_name)
            print('msg_name---->',msg.paid_name)
            print('email_list---->',emails_list)
            content = """
                            <!DOCTYPE html>
                            <html lang="en">
                            <head>
                                <meta charset="UTF-8">
                                <title>OpenDevOps运维提醒邮件</title>
                                <style type="text/css">
                                    p {
                                        width: 100%;
                                        margin: 30px 0 30px 0;
                                        height: 30px;
                                        line-height: 30px;
                                        text-align: center;

                                    }

                                    table {
                                        width: 100%;
                                        text-align: center;
                                        border-collapse: collapse;
                                    }

                                    tr.desc {
                                        background-color: #E8E8E8;
                                        height: 30px;
                                    }

                                    tr.desc td {
                                        border-color: black;
                                    }

                                    td {
                                        height: 30px;
                                    }
                                </style>
                                <style>
                                    .bodydiv {
                                        width: 60%;
                                        margin: 0 auto;
                                    }

                                    .tc {
                                        text-align: center;
                                    }

                                    .content {
                                        margin: 10px 0 10px 30px;
                                    }
                                </style>
                            </head>
                            """
            content += """
                            <div class="bodydiv">
                                Hi, Ops:
                                <div class="content">
                                    你有以下事项提醒需要关注
                                </div>

                            <table>
                                <tr class="desc">
                                    <td>名称</td>
                                    <td>过期时间</td>
                                    <td>提前通知天数</td>
                                </tr>
                            """

            content += """
                                    <tr>
                                    <td>{}</td>
                                    <td>{}</td>
                                    <td>{}</td>
                                     </tr>""".format(msg.paid_name, msg.paid_end_time, msg.reminder_day)

            content += """
                                </table>
                                </div>
                                </body>
                                </html>

                        """
            # send_msg = msg.paid_name + "\n到期时间:" + str(msg.paid_end_time)
            #sm.send_mail("*****@*****.**", "运维信息提醒", send_msg)
            sm.send_mail(",".join(emails_list), '运维提醒信息', content, subtype='html')