コード例 #1
0
ファイル: pw.py プロジェクト: zhouqiw/opsweb
def pw():
    form = MyForm.MyForm_pw()
    if form.submit.data:
        pw = Md5.Md5_make(form.password.data)
        pw1 = form.new_password1.data
        pw2 = form.new_password2.data
        try:
            db = db_op.idc_users
            va = db.query.filter(and_(db.name == g.user,
                                      db.passwd == pw)).first()
            if pw1 == pw2:
                if va:
                    va.passwd = Md5.Md5_make(pw1)
                    db_op.DB.session.commit()
                    db_op.DB.session.close()
                    flash('密码修改成功,请重新登录!')
                    app_resp = make_response(redirect(url_for('index.index')))
                    return app_resp
                else:
                    flash('旧密码错误!')
            else:
                flash('新密码不一致!')
        except Exception as e:
            flash(e)
    return render_template('password.html', Main_Infos=g.main_infos, form=form)
コード例 #2
0
def project_get(project=None):
    try:
        Key = 'op_project_get_%s' % time.strftime('%H%M%S', time.localtime())
        projects = []
        if project:
            db_project = db_op.project_list
            db_servers = db_idc.idc_servers
            vals = db_project.query.with_entities(
                db_project.ip, db_project.ssh_port).filter(
                    db_project.project == project).all()
            if vals:
                for ip, ssh_port in vals:
                    host_vals = db_servers.query.with_entities(
                        db_servers.hostname, db_servers.ip).filter(
                            and_(db_servers.ip == ip,
                                 db_servers.ssh_port == ssh_port)).all()
                    if host_vals:
                        RC.sadd(Key, list(host_vals[0]))
            for val in RC.smembers(Key):
                projects.append(eval(val))
            RC.delete(Key)
            rep = jsonify({
                project: projects,
                'md5': Md5.Md5_make(str(projects)),
                'url': request.url
            })
        return rep
    except Exception as e:
        return jsonify({'error': str(e), 'url': request.url})
コード例 #3
0
ファイル: login.py プロジェクト: znavy/opsweb
def login():
    form = MyForm.MyForm_login()
    form.name.label = '用户名:'
    form.password.label = '密码:'
    user = request.cookies.get('user')
    if user:
        Incr = Redis.incr('%s_Incr' % user)
    else:
        Incr = 0
    if form.submit.data:
        if form.name.data and form.password.data:
            user = form.name.data
            pw = form.password.data
            Key_Incr = '%s_Incr' % user
            Key_Lock = '%s_lock' % user
            try:
                if Incr >= 30:
                    raise flash('该帐号异常登陆,已被锁定3分钟!')
                if Incr >= 5:
                    if form.code.data:
                        if str(form.code.data) != str(session['verify_code']):
                            raise flash('输入验证码错误!')
                    else:
                        raise flash('请输入验证码,看不清点击验证码刷新!')
                va_p = db_op.idc_users.query.filter(
                    and_(db_op.idc_users.name == user,
                         db_op.idc_users.passwd == Md5.Md5_make(pw))).first()
                produce.Async_log(user, request.url)
                if va_p:
                    URL = url_for('index.index')
                    if pw == app.config.get('INIT_OP_PASSWORD'):
                        URL = url_for('pw.pw')
                        flash('请修改初始密码!')
                    timestamp = None
                    if form.remember_me.data:
                        timestamp = check.timestamp(7)
                    ID = produce.Produce(length=24, chars=string.hexdigits)
                    app_resp = make_response(redirect(URL))
                    app_resp.set_cookie('user', user, expires=timestamp)
                    app_resp.set_cookie('ID', ID, expires=timestamp)
                    Redis.set('OP_ID_%s' % user, ID)
                    Redis.delete(Key_Lock)
                    Redis.delete(Key_Incr)
                    return app_resp
                else:
                    Redis.incr(Key_Incr)
                    if Incr >= 30:
                        Redis.set(Key_Lock, 'True')
                        Redis.expire(Key_Incr, 60)
                        Redis.expire(Key_Lock, 180)
                    flash('用户名或者密码错误!')
                    URL = url_for('login.login')
                    app_resp = make_response(redirect(URL))
                    app_resp.set_cookie('user', user)
                    return app_resp
            except Exception as e:
                if 'old' not in str(e):
                    flash(str(e))
    return render_template('login.html', form=form, verify_incr=Incr)
コード例 #4
0
ファイル: login.py プロジェクト: zhouqiw/opsweb
def login():
    form = MyForm.MyForm_login()
    form.name.label = '用户名:'
    form.password.label = '密码:'
    ym = time.strftime('%Y', time.localtime())
    if form.submit.data:
        if form.name.data and form.password.data:
            user = form.name.data
            pw = form.password.data
            try:
                Key_Incr = '%s_Incr' % user
                Key_Lock = 'Lock_login_%s' % user
                if Redis.exists(Key_Incr):
                    Incr = int(Redis.get(Key_Incr))
                else:
                    Incr = 1
                if Redis.exists(Key_Lock):
                    raise flash('该帐号异常登陆,已被锁定1分钟!')
                va_p = db_op.idc_users.query.filter(
                    and_(db_op.idc_users.name == user,
                         db_op.idc_users.passwd == Md5.Md5_make(pw))).first()
                produce.Async_log(user, request.url)
                if va_p:
                    URL = url_for('index.index')
                    if pw == app.config.get('INIT_OP_PASSWORD'):
                        URL = url_for('pw.pw')
                        flash('请修改初始密码!')
                    timestamp = None
                    if form.remember_me.data:
                        timestamp = check.timestamp(7)
                    ID = produce.Produce(length=24, chars=string.hexdigits)
                    app_resp = make_response(redirect(URL))
                    app_resp.set_cookie('user', user, expires=timestamp)
                    app_resp.set_cookie('ID', ID, expires=timestamp)
                    Redis.set('OP_ID_%s' % user, ID)
                    return app_resp
                else:
                    Redis.set(Key_Incr, Incr + 1)
                    if Incr >= 11:
                        Redis.incr(Key_Lock, 'True')
                        Redis.expire(Key_Lock, 60)
                    flash('用户名或者密码错误,还有%s次机会重试!' % (10 - int(Incr)))
                    URL = url_for('login.login')
                    app_resp = make_response(redirect(URL))
                    app_resp.set_cookie('user', user)
                    return app_resp
            except Exception as e:
                if 'old' not in str(e):
                    flash(str(e))
    return render_template('login.html', form=form, ym=ym)
コード例 #5
0
ファイル: approval.py プロジェクト: lukehuang/opsweb-1
def platform_token(action=None, id=None, args=None):
    produce.Async_log(g.user, request.url)
    db_token = db_op.platform_token
    tm = time.strftime('%Y-%m-%d', time.localtime())
    form = MyForm.Form_platform_token()
    tables = ['第三方平台', '连接方式', 'Token', '颁发日期', '失效日期', '管理']
    if action == 'add':
        expire_date = "2999-12-30"
        if id > 0:
            expire_date = datetime.datetime.now() + datetime.timedelta(days=id)
            expire_date = expire_date.strftime('%Y-%m-%d')
        try:
            c = db_token(platform=args,
                         channel='api',
                         token=Md5.Md5_make(tools.Produce(8, string.digits)),
                         award=tm,
                         expire=expire_date)
            db_op.DB.session.add(c)
            db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    if action == 'modify':
        try:
            db_token.query.filter(db_token.id == id).update(
                {db_token.expire: args})
            db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    if action == 'drop':
        try:
            v = db_token.query.filter(db_token.id == id).all()
            for c in v:
                db_op.DB.session.delete(c)
                db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    vals = db_token.query.with_entities(
        db_token.id, db_token.platform, db_token.channel, db_token.token,
        db_token.award, db_token.expire).order_by(desc(db_token.id)).all()
    return render_template('platform_token.html',
                           form=form,
                           vals=vals,
                           tables=tables,
                           tm=tm)
コード例 #6
0
ファイル: deploy.py プロジェクト: zhouqiw/opsweb
def haproxy_reload(Type=None):
    form = MyForm.MyForm_Submit()
    crypto = Md5.crypto(crypto_key)
    code = choice([x for x in range(100)])
    internet = "/haproxy_reload/%s" %crypto.encrypt('internet|%i' %code)
    intranet = "/haproxy_reload/%s" %crypto.encrypt('intranet|%i' %code)
    URL = None
    HA_API = app.config.get('HAPROXY_API')
    if Type:
        Type = crypto.decrypt(Type).split('|')[0]
        if Type == 'internet':
            URL = "%s?type=cw&ip=127.0.0.1:80&domain=test.baihe.com" %HA_API
        if Type == 'intranet':
            URL = "%s?type=cw&ip=127.0.0.1:80&domain=test.baihe.com&intranet=True" %HA_API
        if URL:
            f = requests.get(URL,timeout=10,verify=False)
            Info = f.json()
            if 'result' in f.json():
                Info = f.json()['result']
            return render_template('qrcode.html', INFO=Info)
    return render_template('haproxy_reload.html',Main_Infos=g.main_infos,form=form,internet=internet,intranet=intranet)
コード例 #7
0
ファイル: publish_java.py プロジェクト: zhouqiw/opsweb
def Qrcode(User = None,Grade = None,project=None,project_level = None):
    try:
        tw = int(time.strftime('%w', time.localtime()))
        publish_time = int(time.strftime("%H", time.localtime()))
        crypto = Md5.crypto(crypto_key)
        if User and Grade:
            db = db_op.idc_users
            User = crypto.decrypt(User)
            project = crypto.decrypt(project)
            if db.query.filter(db.name == User).all() and int(Grade) >= 2:
                if tw in (0,6) or publish_time >= 17 or publish_time < 9:
                    verify_key = "{0}_{1}".format(User,project)
                    code = str(produce.Produce(length=6, chars=string.digits))
                    if '0' in code:
                        code.replace('0','1')
                    myRedis.set(verify_key,code)
                    myRedis.expire(verify_key, 900)
                    # send sms
                    mobile = JAVA_Mobile
                    if int(project_level) >= 7:
                        mobile = Mobile
                    result = produce.send_sms(content='上线码:{0} 上线项目:{1} 申请人:{2} 15分钟内有效!'.format(code,project,User), mobile=mobile)
                    if isinstance(result, dict):
                        if result['code'] == 200:
                            INFO = '上线码已成功发送给JAVA领导!'
                            if int(project_level) >= 7:
                                INFO = '上线码已成功发送给曾总!'
                        else:
                            INFO = '上线码发送失败!'
                    else:
                        INFO = '上线码发送失败!'
                else:
                    INFO = "只允许在工作日17点之后或者周末全天申请!"
            else:
                INFO = "该账号无权申请上线码!"
        else:
            INFO = '非法请求信息!'
    except Exception as e:
        INFO = str(e)
    return render_template('qrcode.html',INFO=INFO)
コード例 #8
0
ファイル: vpn_admin.py プロジェクト: zhouqiw/opsweb
def vpn_admin():
    form = MyForm.MyForm_vpn()
    db = db_op.vpn_users
    if form.submit.data:
        users = form.text.data.strip().splitlines()
        vpn_type = form.select_type.data
        users = set(users)
        crypto = Md5.crypto(crypto_key)
        try:
            for user in users:
                if '@' not in user:
                    raise flash('%s格式错误,用户名应为百合个人邮箱账号!' % user)
            action = form.select_action.data
            sender = app.config.get('MAIL_DEFAULT_SENDER')
            if vpn_type == 'intranet':
                vpn_servers = app.config.get('VPN_INTRA')
            if vpn_type == 'internet':
                vpn_servers = app.config.get('VPN_INTER')
            if action == 'query':
                List = []
                for user in users:
                    user = user.strip()
                    val = db.query.with_entities(
                        db.user, db.password).filter(db.user == user).all()
                    if val:
                        List.append([va for va in val[0]])
                    else:
                        flash('%s 账号不存在!' % user)
                if List:
                    List = [(list[0], list[1]) for list in List]
                    return render_template('vpn_admin_show.html',
                                           Main_Infos=g.main_infos,
                                           user_list=List)
            elif action == 'add':
                for user in users:
                    user = user.strip()
                    pw = produce.Produce(13)
                    if db.query.filter(db.user == user).all():
                        flash('%s 账号已存在' % user)
                        continue
                    msg = Message("VPN账号信息", sender=sender, recipients=[user])
                    msg.html = '<p>用户名:%s</p><p> 密码:%s</p><p> VPN地址:%s</p><p><font color="red">账号5分钟后开通,请妥善保管此封邮件,勿邮件回复!</font></p>' % (
                        user, pw, vpn_servers)
                    with app.open_resource("%s/../doc/vpn_conf.docx" %
                                           page_vpn_admin.root_path) as f:
                        msg.attach("vpn_conf.docx", "text/docx", f.read())
                    try:
                        with app.app_context():
                            mail.send(msg)
                            db_op.DB.session.add(
                                db(user=user,
                                   password=crypto.encrypt(pw),
                                   status=1,
                                   vpn_type=vpn_type))
                            db_op.DB.session.commit()
                    except Exception as e:
                        flash(e)
                    else:
                        flash('%s 账号开通完毕,通知邮件已发送.' % user)
            elif action == 'del':
                for user in users:
                    user = user.strip()
                    db.query.filter(db.user == user).update({db.status: 2})
                    db_op.DB.session.commit()
                    flash('%s 账号已关闭!' % user)
            elif action == 'change':
                for user in users:
                    user = user.strip()
                    db.query.filter(db.user == user).update({
                        db.status:
                        1,
                        db.vpn_type:
                        vpn_type
                    })
                    db_op.DB.session.commit()
                    flash(('%s vpn类型已变更!' % user))
        except Exception as e:
            flash(e)
        return render_template('Message_static.html', Main_Infos=g.main_infos)
    return render_template('vpn_admin.html',
                           Main_Infos=g.main_infos,
                           form=form)
コード例 #9
0
def login():
    try:
        try:
            token = tools.Produce(length=24, chars=string.hexdigits)
        except Exception as e:
            logging.error(e)
        ym = time.strftime('%Y', time.localtime())
        session['Menu'] = {}
        #钉钉验证授权
        if tools.http_args(request, 'code') and tools.http_args(
                request, 'state') == 'STATE':
            db_auth = db_op.user_auth
            code = tools.http_args(request, 'code')
            #获取token
            try:
                url = "https://oapi.dingtalk.com/sns/gettoken?appid=dingoadq3qon8zb34vzdff&appsecret=Tu6IlXjTn1m4vqrOA580xLOt2VbOK26bVu3sBOtvp0MnqIp2zpcwkL3qVpqAT7rG"
                if ENV == 'dev':
                    url = "https://oapi.dingtalk.com/sns/gettoken?appid=dingoa7wymhx6dbeffjels&appsecret=I-v3OXL1hFKYZlJ3b6pqABmoNGYREXePpdzQ5JaSK8DqJdQyn_1J3wEUYBTpdiE_"
                r = requests.get(url)
                access_token = r.json()['access_token']
                r = requests.post(
                    "https://oapi.dingtalk.com/sns/get_persistent_code?access_token=%s"
                    % access_token,
                    data=json.dumps({"tmp_auth_code": code}))
                openid = r.json()['openid']
                persistent_code = r.json()['persistent_code']
                r = requests.post(
                    "https://oapi.dingtalk.com/sns/get_sns_token?access_token=%s"
                    % access_token,
                    data=json.dumps({
                        "openid": openid,
                        "persistent_code": persistent_code
                    }))
                sns_token = r.json()['sns_token']
                #获取用户信息
                r = requests.get(
                    'https://oapi.dingtalk.com/sns/getuserinfo?sns_token=%s' %
                    sns_token)
                user_info = r.json()['user_info']
                nick = user_info['nick']
                dingId = user_info['dingId']
            except Exception as e:
                logging.error(e)
            #授权用户登陆
            if nick and dingId:
                try:
                    val = db_auth.query.filter(
                        and_(db_auth.dingId == dingId,
                             db_auth.openid == openid)).all()
                    if val:
                        db_auth.query.filter(
                            and_(db_auth.dingId == dingId,
                                 db_auth.openid == openid)).update({
                                     db_auth.token:
                                     token,
                                     db_auth.update_time:
                                     time.strftime('%Y-%m-%d %H:%M:%S',
                                                   time.localtime())
                                 })
                        db_op.DB.session.commit()
                        URL = url_for('main')
                        timestamp = check.timestamp(7)
                    else:
                        #跳转至权限申请页
                        URL = url_for('approval.apply')
                        timestamp = check.timestamp(1)
                except Exception as e:
                    logging.error(e)
                app_resp = make_response(redirect(URL))
                try:
                    app_resp.set_cookie('user',
                                        Md5.Md5_make(nick),
                                        expires=timestamp,
                                        path='/')
                    app_resp.set_cookie('openid',
                                        Md5.Md5_make(openid),
                                        expires=timestamp,
                                        path='/')
                    app_resp.set_cookie('dingId',
                                        Md5.Md5_make(dingId),
                                        expires=timestamp,
                                        path='/')
                    app_resp.set_cookie('token',
                                        Md5.Md5_make(token),
                                        expires=timestamp,
                                        path='/')
                except Exception as e:
                    logging.error(e)
                else:
                    Redis.set('OP_verify_%s' % dingId, token)
                    Redis.set('OP_token_%s' % Md5.Md5_make(token), token)
                    Redis.set('OP_dingId_%s' % Md5.Md5_make(dingId), dingId)
                    Redis.set('OP_user_%s' % Md5.Md5_make(nick), nick)
                    Redis.set('OP_openid_%s' % Md5.Md5_make(openid), openid)
                return app_resp
    except Exception as e:
        flash('登录失败!')
        logging.error(e)
    finally:
        db_op.DB.session.remove()
    return render_template('login.html', ym=ym, ENV=ENV)
コード例 #10
0
def op_user():
    form = MyForm.Myform_op_user()
    db = db_op.idc_users
    sender = "*****@*****.**"
    if form.submit.data:
        users = form.text.data.splitlines()
        action = form.select.data
        for user in users:
            if '@baihe.com' in user:
                if action == 'unlock':
                    Redis.delete('%s_lock' % user)
                    flash('{0}账号已解锁!'.format(user))
                val = db.query.with_entities(db.name).filter(
                    and_(db.name == user, db.grade == 2)).all()
                if action == 'query':
                    if val:
                        flash('{0}账号已存在!'.format(user))
                    else:
                        flash('{0}账号不存在!'.format(user))
                if action == 'add':
                    if val:
                        flash('{0}账号已存在!'.format(user))
                    else:
                        PW = Md5.Md5_make(produce.Produce())
                        pw = Md5.Md5_make(PW)
                        # 开通成功后再发送邮件
                        msg = Message("OP账号信息",
                                      sender=sender,
                                      recipients=[user])
                        msg.html = '<p>用户名:%s</p><p> 密码:%s</p><p>访问地址:http://xxx.baihe.com/</p><p><font color="red">勿邮件回复!</font></p>' % (
                            user, PW)
                        with app.app_context():
                            try:
                                mail.send(msg)
                            except Exception as e:
                                flash(e)
                                flash('%s 邮件发送失败!' % user)
                            else:
                                db_op.DB.session.add(
                                    db(name=user, passwd=pw, grade=2))
                                db_op.DB.session.commit()
                                flash('%s 账号开通成功,通知邮件已发送.' % user)
                if action == 'del':
                    try:
                        val = db.query.filter(
                            and_(db.name == user, db.grade == 2)).all()
                        if val:
                            for c in val:
                                db_op.DB.session.delete(c)
                                db_op.DB.session.commit()
                            flash('{0}账号删除成功!'.format(user))
                        else:
                            flash('{0}账号不存在!'.format(user))
                    except Exception as e:
                        flash(e)
                if action == 'init':
                    if val:
                        pw = Md5.Md5_make('123456')
                        db.query.filter(and_(db.name == user,
                                             db.grade == 2)).update(
                                                 {db.passwd: pw})
                        db_op.DB.session.commit()
                        flash('{0}账号初始化成功,初始化密码:123456'.format(user))
                    else:
                        flash('{0}账号不存在!'.format(user))
            else:
                flash('{0}账号格式不正确,账号应为个人邮箱!'.format(user))
        return render_template('Message_static.html')
    return render_template('op_user.html', form=form)
コード例 #11
0
def publish_code():
    try:
        timestamp = None
        db_token = db_op.platform_token
        params = request.json
        GRAY = {'Flase': 0, 'True': 1}
        # 检查时间戳是否存在
        if 'timestamp' in params['data']:
            timestamp = params['data']['timestamp']
        else:
            return jsonify({'status': 'timestamp is null', 'timestamp': None})
        #md5对比验证数据
        new_md5 = Md5.Md5_make(params['data'])
        if new_md5 == params['data_md5']:
            params = params['data']
            token = params['access_token']
            #验证token是否有效
            vals = db_token.query.filter(
                and_(
                    db_token.token == token, db_token.expire > time.strftime(
                        '%Y-%m-%d', time.localtime()))).all()
            if vals:
                user = params['proposer']
                package_url = params['package_url']
                #检查压缩包下载地址格式
                if not package_url.endswith(
                        '.zip') and not package_url.endswith('.war'):
                    return jsonify({
                        'status': 'the package must be zip or war',
                        'timestamp': timestamp
                    })
                #获取详细参数
                describe = params['describe']
                package_md5 = params['package_md5']
                package_type = params['package_type']
                publish_type = params['publish_type']
                restart = params['restart']
                execute = params['execute']
                check_url = params['check_url']
                rb_project = params['project_name']
                rb_version = params['project_version']
                callback_url = params['callback_url']
                gray = GRAY[params['gray']]
                #生成随机key种子
                K = '%s_%s' % (token,
                               tools.Produce(length=8, chars=string.digits))
                Msg_Key = '%s_publish_msg' % K
                INFOS = {
                    'package_url': package_url,
                    'package_md5': package_md5,
                    'package_type': package_type,
                    'publish_type': publish_type,
                    'user': user,
                    'describe': describe.replace('"', '').replace("'", ''),
                    'gray': gray,
                    'restart': restart,
                    'execute': execute,
                    'check_url': check_url.replace('https', 'http'),
                    'project': rb_project,
                    'version': rb_version,
                    'channel': 'api',
                    'callback_url': callback_url,
                    'token': token,
                    'timestamp': timestamp
                }
                #启动代码分发控制中心
                Scheduler = produce.Scheduler_publish()
                Scheduler = Scheduler.Scheduler_mem(
                    task_publish.Publish_center, [INFOS, Msg_Key, K])
                Scheduler.start()
                return jsonify({'status': 'ok', 'timestamp': timestamp})
            else:
                return jsonify({
                    'status': 'token deny',
                    'timestamp': timestamp
                })
        else:
            return jsonify({
                'status': 'data_md5 error',
                'timestamp': timestamp
            })
    except Exception as e:
        logging.error(e)
        return jsonify({'status': str(e), 'timestamp': timestamp})
    finally:
        db_op.DB.session.remove()
コード例 #12
0
ファイル: project_apply.py プロジェクト: newbelee/opsweb
def project_apply_show(ID=None):
    crypto_key = app.config.get('CRYPTO_KEY')
    crypto = Md5.crypto(crypto_key)
    db = db_op.project_apply
    if ID:
        if '&' in ID:
            id = crypto.decrypt(ID.split('&')[0])
            action = ID.split('&')[1].split('=')[-1]
            if action == 'fail':
                Infos = db.query.with_entities(db.project, db.describe, db.content, db.sender).filter(db.id == id).all()
                if Infos:
                    Infos = Infos[0]
                    Receiver = Infos[-1]
                    if '@' not in  Receiver:
                        Receiver = '*****@*****.**' %Receiver
                    Content = Infos[2].split(';')
                    msg = Message("提测项目%s被退回" % Infos[0], sender=sender, recipients=[Receiver], cc=[sender])
                    msg.html = '<p>1、项目描述:</p>' \
                               '<p><strong>%s</strong></p>' \
                               '<p>2、提测版本:</p>' \
                               '<p><strong>%s</strong></p>' \
                               '<p><strong>%s</strong></p>'  % (Infos[1],Content[0],Content[1])
                    with app.app_context():
                        try:
                            mail.send(msg)
                        except Exception as e:
                            loging.write(e)
                        else:
                            db.query.filter(db.id == int(id)).update({db.status:'2'})
                            db_op.DB.session.commit()
        else:
            ID = crypto.decrypt(ID)
            Infos = db.query.with_entities(db.project, db.describe, db.content, db.Rollback).filter(db.id == ID).all()
            if Infos:
                Infos = Infos[0]
                Content = Infos[2].split(';')
                Rollback = Infos[-1].split(';')
                msg = Message("%s项目申请上线" % Infos[0], sender=sender, recipients=[sender], cc=[mails['leader']])
                msg.html = '<p>1、项目描述:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p>2、上线版本:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p>3、回滚版本:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p><strong>%s</strong></p>' % (Infos[1], Content[0], Content[1],Rollback[0],Rollback[1])
                with app.app_context():
                    try:
                        mail.send(msg)
                    except Exception as e:
                        loging.write(e)
                    else:
                        db.query.filter(db.id == int(ID)).update({db.status: '1'})
                        db_op.DB.session.commit()
    tables = ('提测项目', '类别', '项目描述', '提测版本', '发起人', '后续操作')
    Vals = db.query.with_entities(db.id,db.project,db.types,db.describe,db.content,db.sender).filter(db.status == '0').order_by(db.id).all()
    projects =[]
    for info in [list(info) for info in Vals]:
        info[0]= (crypto.encrypt(info[0]),'%s&result=fail'%crypto.encrypt(info[0]))
        projects.append(info)
    return render_template('project_apply_show.html',Main_Infos=g.main_infos,projects = projects,tables=tables)
コード例 #13
0
ファイル: publish_java.py プロジェクト: zhouqiw/opsweb
def publish_java():
    produce.Async_log(g.user, request.url)
    K = '%s_%s' %(g.user,g.secret_key)
    messageKey = '%s_publish_java' % K
    publish_key = '%s_publish_key' % K
    qrcode_url = None
    form = MyForm.MyForm_publishJboss()
    if form.submit.data:
        Action = form.selectAction.data
        Type = int(form.selectType.data)
        Gray = form.Gray.data
        Way = form.selectWay.data
        code = form.code.data
        work = form.selectwork.data
        changelog = form.changelog.data
        tags = form.text.data.strip().splitlines()
        if tags and changelog:
            try:
                if myRedis.exists(messageKey):
                    raise flash('上线操作过于频繁,请稍等%s秒......' %myRedis.ttl(messageKey))
                assert len(tags) == 1, '错误:只能同时上线一个项目!'
                warTagName = tags[0]
                version = '0.0.0'
                if Action == 'restart':
                    warname = warTagName
                elif Way == 'SVN':
                    assert '.war.zip' in warTagName, '错误:格式错误!格式应为: baihe-xxxx-x.x.x.war.zip'
                    warname = warTagName.split('-')[:-1]
                    version = warTagName.split('-')[-1].replace('.war.zip','')
                    warname = '-'.join(warname) + '.war'
                elif Way == 'GIT':
                    warname = "{0}.war".format(warTagName.split('/')[-1])
            except Exception as e:
                flash(e)
            else:
                try:
                    project_db = db_op.project_level
                    project_level = project_db.query.with_entities(project_db.level).filter(project_db.project == warname).all()
                    # 测外不强制项目等级
                    if Type == 2:
                        if project_level:
                            project_level = int(project_level[0][0])
                        else:
                            project_level = 1
                    else:
                        if project_level:
                            project_level = int(project_level[0][0])
                            crypto = Md5.crypto(crypto_key)
                            qrcode_url = "https://op.baihe.com/qrcode_java/{0}/{1}/{2}/{3}".format(crypto.encrypt(g.user),g.grade,crypto.encrypt(warname),project_level)
                        else:
                            raise flash('没有找到该项目的对应项目等级!')
                    publish_time = time.strftime("%H", time.localtime())
                    if code:
                        verify_key = "{0}_{1}".format(g.user,warname)
                        verify_code = myRedis.get(verify_key)
                        if verify_code == str(code):
                            myRedis.lpush(messageKey, '    --->verify code pass!')
                            myRedis.expire(messageKey,30)
                            myRedis.delete(verify_key)
                        else:
                            raise flash('%s 该上线码验证不通过!' %str(code))
                    else:
                        # 用户权限及行为判断
                        tw = int(time.strftime('%w', time.localtime(time.time())))
                        if g.grade >= 2 and Type == 1 and Action == 'publish':
                            if project_level >= 5:
                                raise flash('该项目等级为%s级,需申请上线码!' % project_level)
                            if tw in (2, 4):
                                if project_level <= 4 and (int(publish_time) >= 17 or int(publish_time) <= 9):
                                    raise flash('仅允许在10-17点时间段进行上线操作,需申请上线码!')
                            else:
                                raise flash('4级及以下常规项目只限在周二和周四上线,修复BUG需申请上线码!')
                        if g.grade >= 2 and Action == 'rollback':
                            raise flash('没有权限进行回滚操作!')
                    dbTable = db_op.java_list
                    #灰度发布
                    if Gray:
                        ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type,dbTable.Gray == '1')).limit(1).all()
                        if not ServerList:
                            ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type)).limit(1).all()
                            if ServerList:
                                for ip, username in ServerList:
                                    dbTable.query.filter(db_op.DB.and_(dbTable.ip == ip, dbTable.user == username)).update({dbTable.Gray:'1'})
                            else:
                                raise flash('%s 没有在上线列表中找到!' % warname)
                    else:
                        ServerList = dbTable.query.with_entities(dbTable.ip,dbTable.user).filter(db_op.DB.and_(dbTable.project == warname,dbTable.type == Type)).all()
                        if Type == 1:
                            ServerList.append(('172.16.4.188','java'))
                    if ServerList:
                        myRedis.lpush(messageKey, 'check security policy......')
                        myRedis.expire(messageKey, 30)
                        information = {}
                        information['warname'] = warname
                        information['warTagName'] = warTagName
                        information['ServerList'] = ServerList
                        information['Action'] = Action
                        information['Gray'] = Gray
                        information['Type'] = Type
                        information['Way']  = Way
                        myRedis.lpush(publish_key,information)
                        mysql_operation = Mysql.mysql_op(g.user,Action,Type,warname,version,Gray,work,project_level,changelog)
                        mysql_operation.op_operation()
                        Scheduler = produce.Scheduler_publish()
                        Scheduler = Scheduler.Scheduler_mem(java_publish.java_publish,publish_key,messageKey)
                        Scheduler.start()
                        myRedis.lpush(messageKey, '    --->check pass!')
                        myRedis.lpush(messageKey, '-' * 80 + '\n')
                    else:
                        raise flash('%s 没有在上线列表中找到!' % warname)
                except Exception as e:
                    if 'old' not in str(e):
                        flash(e)
                    if qrcode_url:
                        return render_template('java_publish.html',Main_Infos=g.main_infos, form=form, qrcode_url=qrcode_url)
                else:
                    return render_template('java_publish_show.html',Main_Infos=g.main_infos)
        else:
            flash("错误:文本框内容不能为空!")
    return render_template('java_publish.html',Main_Infos=g.main_infos,form=form,qrcode_url=qrcode_url)
コード例 #14
0
ファイル: vpn_admin.py プロジェクト: newbelee/opsweb
def vpn_admin():
    form = MyForm.MyForm_vpn()
    db = db_op.vpn_users
    if form.submit.data:
        users = form.text.data.strip().splitlines()
        vpn_type = form.select_type.data
        users = set(users)
        crypto = Md5.crypto(crypto_key)
        try:
            for user in users:
                if '@' not in user:
                    raise flash('%s格式错误,用户名应为百合个人邮箱账号!'%user)
            action = form.select_action.data
            sender = app.config.get('MAIL_DEFAULT_SENDER')
            if vpn_type == 'intranet':
                vpn_servers = app.config.get('VPN_INTRA')
            if vpn_type == 'internet':
                vpn_servers = app.config.get('VPN_INTER')
            if action == 'query':
                List = []
                for user in users:
                    user = user.strip()
                    val = db.query.with_entities(db.user,db.password).filter( db.user == user).all()
                    if val:
                        List.append([va for va in val[0]])
                    else:
                        flash('%s 账号不存在!' %user)
                if List:
                    List = [(list[0],list[1]) for list in List]
                    return render_template('vpn_admin_show.html',Main_Infos=g.main_infos, user_list=List)
            elif action == 'add':
                for user in users:
                    user = user.strip()
                    pw = produce.Produce(13)
                    if db.query.filter(db.user == user).all():
                        flash('%s 账号已存在'%user)
                        continue
                    msg = Message("VPN账号信息",sender=sender,recipients=[user])
                    msg.html = '<p>用户名:%s</p><p> 密码:%s</p><p> VPN地址:%s</p><p><font color="red">账号5分钟后开通,请妥善保管此封邮件,勿邮件回复!</font></p>' %(user,pw,vpn_servers)
                    with app.open_resource("%s/../doc/vpn_conf.docx" %page_vpn_admin.root_path) as f:
                        msg.attach("vpn_conf.docx", "text/docx", f.read())
                    try:
                        with app.app_context():
                            mail.send(msg)
                            db_op.DB.session.add(db(user=user, password=crypto.encrypt(pw), status=1,vpn_type=vpn_type))
                            db_op.DB.session.commit()
                    except Exception as e:
                        flash(e)
                    else:
                        flash('%s 账号开通完毕,通知邮件已发送.' %user)
            elif action == 'del':
                for user in users:
                    user = user.strip()
                    db.query.filter(db.user == user).update({db.status:2})
                    db_op.DB.session.commit()
                    flash('%s 账号已关闭!' %user)
            elif action == 'change':
                for user in users:
                    user = user.strip()
                    db.query.filter(db.user == user).update({db.status:1,db.vpn_type:vpn_type})
                    db_op.DB.session.commit()
                    flash(('%s vpn类型已变更!' %user))
        except Exception as e:
            flash(e)
        return render_template('Message_static.html',Main_Infos=g.main_infos)
    return render_template('vpn_admin.html',Main_Infos=g.main_infos,form=form)
コード例 #15
0
ファイル: project_apply.py プロジェクト: zhouqiw/opsweb
def project_apply_show(ID=None):
    crypto_key = app.config.get('CRYPTO_KEY')
    crypto = Md5.crypto(crypto_key)
    db = db_op.project_apply
    if ID:
        if '&' in ID:
            id = crypto.decrypt(ID.split('&')[0])
            action = ID.split('&')[1].split('=')[-1]
            if action == 'fail':
                Infos = db.query.with_entities(
                    db.project, db.describe, db.content,
                    db.sender).filter(db.id == id).all()
                if Infos:
                    Infos = Infos[0]
                    Receiver = Infos[-1]
                    if '@' not in Receiver:
                        Receiver = '*****@*****.**' % Receiver
                    Content = Infos[2].split(';')
                    msg = Message("提测项目%s被退回" % Infos[0],
                                  sender=sender,
                                  recipients=[Receiver],
                                  cc=[sender])
                    msg.html = '<p>1、项目描述:</p>' \
                               '<p><strong>%s</strong></p>' \
                               '<p>2、提测版本:</p>' \
                               '<p><strong>%s</strong></p>' \
                               '<p><strong>%s</strong></p>'  % (Infos[1],Content[0],Content[1])
                    with app.app_context():
                        try:
                            mail.send(msg)
                        except Exception as e:
                            loging.write(e)
                        else:
                            db.query.filter(db.id == int(id)).update(
                                {db.status: '2'})
                            db_op.DB.session.commit()
        else:
            ID = crypto.decrypt(ID)
            Infos = db.query.with_entities(
                db.project, db.describe, db.content,
                db.Rollback).filter(db.id == ID).all()
            if Infos:
                Infos = Infos[0]
                Content = Infos[2].split(';')
                Rollback = Infos[-1].split(';')
                msg = Message("%s项目申请上线" % Infos[0],
                              sender=sender,
                              recipients=[sender],
                              cc=[mails['leader']])
                msg.html = '<p>1、项目描述:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p>2、上线版本:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p>3、回滚版本:</p>' \
                           '<p><strong>%s</strong></p>' \
                           '<p><strong>%s</strong></p>' % (Infos[1], Content[0], Content[1],Rollback[0],Rollback[1])
                with app.app_context():
                    try:
                        mail.send(msg)
                    except Exception as e:
                        loging.write(e)
                    else:
                        db.query.filter(db.id == int(ID)).update(
                            {db.status: '1'})
                        db_op.DB.session.commit()
    tables = ('提测项目', '类别', '项目描述', '提测版本', '发起人', '后续操作')
    Vals = db.query.with_entities(
        db.id, db.project, db.types, db.describe, db.content,
        db.sender).filter(db.status == '0').order_by(db.id).all()
    projects = []
    for info in [list(info) for info in Vals]:
        info[0] = (crypto.encrypt(info[0]),
                   '%s&result=fail' % crypto.encrypt(info[0]))
        projects.append(info)
    return render_template('project_apply_show.html',
                           Main_Infos=g.main_infos,
                           projects=projects,
                           tables=tables)
コード例 #16
0
ファイル: publish_php.py プロジェクト: zhouqiw/opsweb
def publish_php():
    produce.Async_log(g.user, request.url)
    K = '%s_%s' %(g.user,g.secret_key)
    Key = '%s_publish_php' %K
    publish_key = '%s_publish_key' %K
    qrcode_url = None
    form = MyForm.MyForm_php()
    if form.submit.data:
        try:
            if Redis.exists(Key):
                raise flash('上线操作过于频繁,请稍等%s秒......' %Redis.ttl(Key))
            if form.text.data and form.changelog.data:
                action = form.selectaction.data
                Type = int(form.selecttype.data)
                Way = form.selectWay.data
                if Type == 1:
                    platfrom = '线上'
                if Type == 2:
                    platfrom = '测外'
                Tags = form.text.data.strip().splitlines()
                Gray = form.Gray.data
                code = form.code.data
                work = form.selectwork.data
                changelog = form.changelog.data
                if Way == 'SVN':
                    if len(Tags) > 1:
                        raise flash('错误:只能同时上线一个项目!')
                    else:
                        for line in Tags:
                            if line.startswith('#') or not line.split():
                                continue
                            m = re.match(r'[0-9]', line)
                            if m:
                                raise flash('错误:不能以数字开头!')
                            if not line.startswith('/'):
                                raise flash('错误:' + line + '路径必须以"/"开头!')
                            path = line.strip()
                            path = path.replace('\\', '/')
                            App = path.split('/')
                            if len(App)<4:
                                raise flash('错误:路径错误,无法获取项目名!')
                            App = App[3]
                            if len(path.split('-')) >= 2:
                                version = path.split('-')[-1]
                            else:
                                raise flash('错误:项目名称格式错误!')
                            if version.endswith('.zip'):
                                version = version.replace('.zip', '')
                elif Way == 'GIT':
                    if len(Tags) != 2:
                        raise flash('错误:GIT上线格式不对!')
                    elif not Tags[0].strip().startswith('http://'):
                        raise flash('错误:' + Tags[0] + '路径需以"http://"开头!')
                    elif not Tags[0].strip().endswith('.git'):
                        raise flash('错误:' + Tags[0] + '应该以".git"结尾!')
                    elif not Tags[1].strip().startswith('tag-'):
                        raise flash('错误:输入的tag版本号格式错误!')
                    path = ';'.join(Tags)
                    path = path.replace('http://git.baihe.com/', '/')
                    App = Tags[0].strip().split('/')[-1]
                    App = App.split('.')[0]
                    version = Tags[1].split('-')[-1]
            else:
                raise flash('错误:文本框内容不能为空!')
        except Exception as e:
            if 'old' not in str(e):
                flash(e)
        else:
            try:
                project_db = db_op.project_level
                project_level = project_db.query.with_entities(project_db.level).filter(project_db.project == App).all()
                #测外不强制项目等级
                if Type == 2:
                    if project_level:
                        project_level = int(project_level[0][0])
                    else:
                        project_level = 1
                else:
                    if project_level:
                        project_level = int(project_level[0][0])
                        crypto = Md5.crypto(crypto_key)
                        qrcode_url = "https://op.baihe.com/qrcode_php/{0}/{1}/{2}/{3}".format(crypto.encrypt(g.user),g.grade,crypto.encrypt(App),project_level)
                    else:
                        raise flash('没有找到该项目的对应项目等级!')
                publish_time = time.strftime("%H", time.localtime())
                if code:
                    verify_key = "{0}_{1}".format(g.user,App)
                    verify_code = Redis.get(verify_key)
                    if verify_code == str(code):
                        Redis.lpush(Key, '    --->verify code pass!')
                        Redis.expire(Key, 30)
                        Redis.delete(verify_key)
                        code_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        db = db_op.publish_code
                        db_op.DB.session.add(
                            db(project=App, code=str(code), platfrom=platfrom, user=g.user, Time=code_time))
                        db_op.DB.session.commit()
                    else:
                        raise flash('%s 该上线码验证不通过!' %str(code))
                else:
                    # 用户权限及行为判断
                    tw = int(time.strftime('%w',time.localtime(time.time())))
                    if g.grade >= 2 and Type == 1 and action == 'publish':
                        if project_level >= 5:
                            raise flash('该项目等级为%s级,需申请上线码!' % project_level)
                        if tw in (2,4):
                            if project_level <= 4 and (int(publish_time) >= 17 or int(publish_time) <= 9):
                                raise flash('仅允许在10-17点时间段进行上线操作,需申请上线码!')
                        else:
                            raise flash('4级及以下常规项目只限在周二和周四上线,修复BUG需申请上线码!')
                    if g.grade >= 2 and action == 'rollback':
                        raise flash('没有权限进行回滚操作!')
                db = db_op.php_list
                if Gray:
                    if App == 'baihePhpGlobalLibrary_publish':
                        val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'baihe')).limit(1).all()
                        if not val:
                            val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'baihe')).limit(1).all()
                    elif App == 'Baihe':
                        val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'hunli')).limit(1).all()
                        if not val:
                            val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'hunli')).limit(1).all()
                    else:
                        val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.project == '%s' % App)).limit(1).all()
                        if not val:
                            val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' % App, db.type == '%i' % Type)).limit(1).all()
                    if val:
                        sip = [v[0].encode('UTF-8') for v in val if v]
                        db.query.filter(and_(db.project == App, db.ip == sip[0])).update({db.Gray: '1'})
                    else:
                        raise flash('%s 没有在上线列表中找到!' % App)
                else:
                    if App == 'baihePhpGlobalLibrary_publish':
                        val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'baihe')).all()
                    elif App == 'Baihe':
                        val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'hunli')).all()
                    else:
                        val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' %App,db.type == '%i' %Type)).all()
                    if val:
                        val = set(val)
                        sip = [v[0].encode('UTF-8') for v in val if v]
                        if Type == 1:
                            sip.append('172.16.4.188')
                    else:
                        raise flash('%s 没有在上线列表中找到!' %App)
                Redis.lpush(Key, 'check security policy......')
                Redis.expire(Key, 30)
                Info = {}
                Info['action'] = action
                Info['path'] = path
                Info['app'] = App
                Info['sip'] = sip
                Info['gray'] = Gray
                Info['Type'] = Type
                Info['Way'] = Way
                Redis.lpush(publish_key,Info)
                mysql_operation = Mysql.mysql_op(g.user,action,Type,App,version,Gray,work,project_level,changelog)
                mysql_operation.op_operation()
                Scheduler = produce.Scheduler_publish()
                Scheduler = Scheduler.Scheduler_mem(php_publish.php_publish,publish_key,Key)
                Scheduler.start()
                Redis.lpush(Key,'    --->check pass!')
                Redis.lpush(Key,'-'*80+'\n')
            except Exception as e:
                if 'old' not in str(e):
                    flash(e)
                if qrcode_url:
                    return render_template('php_publish.html',Main_Infos=g.main_infos, form=form, qrcode_url=qrcode_url)
            else:
                return render_template('php_publish_show.html',Main_Infos=g.main_infos)
    return render_template('php_publish.html',Main_Infos=g.main_infos,form=form,qrcode_url = qrcode_url)