Ejemplo n.º 1
0
Archivo: hb.py Proyecto: whitefirer/hb
def create_hb201901(chart_data, node_id, click_time):
    answer = bytes(app.config['HB201901_CODE'], 'utf-8')
    answer_tip = 'I also want to know'
    question_tip = '2**73+37 is a prime number?'
    failed_tip = '胜败乃兵家常事,少侠请从头再来'
    tips = {
        '-1': '好疼啊',
        '0': '点疼我了~',
        '1': '2019新年快乐!\n难度:Easy',
        '2': '2是第一个素数',
        '16': 'AES的16位key是什么?',
        '37': '答案的关键',
        '73': '谢耳朵最喜欢的数字',
        '2019': '新年快乐~',
        '9102': '我有一个疑问\n需要2019解答',
        '9444732965739290427429': '恭喜你找到了!'
    }
    #log.debug('hb201901 tips: %s' % tips)

    tip = tips.get(str(node_id))

    try:
        click_time = '%10.06f' % click_time
        secret_key = click_time.replace('.', '')
        log.debug('Crypt secret_key: %s' % secret_key)
        node_id = int(node_id)
        create_node(chart_data, node_id, node_id)
    except Exception as e:
        log.error(str(e))
        node_id = 1
        tip = failed_tip

    if tip:
        name = '0'
        if node_id == 2019:
            cpt = Crypt(secret_key)
            name = cpt.encrypt(answer_tip)
        if node_id == 9102:
            cpt = Crypt(secret_key)
            name = cpt.encrypt(question_tip)
        elif node_id == 9444732965739290427429:  # 2**73+37
            cpt = Crypt(secret_key)
            name = cpt.encrypt(base64.b64encode(answer).decode('utf-8'))
        create_tips(chart_data, tip, name)
        log.debug('create_hb201901 tip:%s' % tip)

    if node_id > 0:
        create_nodes(chart_data, [int(node_id)], 3)

    if tip == failed_tip:
        return False

    return True
Ejemplo n.º 2
0
def check_jobs_list(params):

    try:
        params["job_name"] = str(params.get("job_name", ''))
        params["region"] = str(params.get("region") or '')
        params["time_scale"] = int(params.get("time_scale") or 0)
        params["page"] = int(params.get("page") or 1)

        return params

    except Exception as e:
        log.error('查询职位列表出现错误 [Error: %s]' % e)
        abort(
            HTTPStatus.InternalServerError,
            **make_resp(status=APIStatus.InternalServerError,
                        msg='查询职位列表出现错误'))
Ejemplo n.º 3
0
def on_admin_push(request):
    #TODO:要求用户验证
    #前端传过来的是序列化后的json字符串, 需要loads一下
    watcher=None
    try:
        if request.session['account']!=settings.SUPER_USER:
            try:
                Watcher.objects.get(account=request.session['account'],iswatching=True)
            except:
                raise Exception(unicode("非法用户尝试修改值班干事"))
        push_json_str=request.POST['data']
        push_json=json.loads(push_json_str)
        for item in push_json['watch_list']:
            #检查输入
            log.debug('on_admin_push','for item start checking')
            keys = ['account','watchsum','name','spnumber','iswatching','lpnumber','type']
            for key in keys:
                if key not in item:
                    raise Exception('incomplete data')
                if check.is_clean_input(key,item[key]) == False:
                    print key, item[key]
                    raise Exception('unsafe data')
            log.debug('on_admin_push','for item end checking')
            #先删除
            log.debug('on_admin_push','delete items')
            if item.get('type')=='delete':
                is_logined = (item['account']==request.session['account'])
                log.debug('on_admin_push','%s deleted'%item['account'])
                Watcher.objects.all().filter(account=item['account']).delete()
                if is_logined: 
                    del request.session['account']
            else:
                if item.get('type')=='new':
                    default_password=hashlib.md5(item['account']).hexdigest()
                    default_password=hashlib.sha1(default_password).hexdigest()
                    log.debug('on_admin_push','trying to create new watcher %s'%item['account'])
                    watcher=Watcher(
                        account=B(item['account']),
                        name=B(item['name']),
                        lpnumber=B(item['lpnumber']),
                        spnumber=B(item['spnumber']),
                        password=B(default_password),
                        watchsum=0,
                        iswatching=False)
                    log.debug('on_admin_push','succeed to create new watcher')
                else:
                    log.debug('on_admin_push','trying to get item %s'%item['account'])
                    watcher=Watcher.objects.get(account=item['account'])
                    log.debug('on_admin_push','succeed to get item')
                if('yes'==item['iswatching']):
                    watcher.iswatching=True
                elif('no'==item['iswatching']):
                    watcher.iswatching=False
                    if watcher.account == request.session['account'] and watcher.account!=settings.SUPER_USER:
                        del request.session['account']
                log.info('on_admin_push','after setting watching state')
                watcher.save()
                log.info('on_admin_push','after save')
        return HttpResponse(json.dumps({'flag_succeed':'true',}))

    except Exception as e:
        log.error('exception in on_admin_push:',unicode(e))
        error=Error(what=B(unicode(e)))
        error.save()
        return HttpResponse(json.dumps({'flag_succeed':'false',}))
Ejemplo n.º 4
0
def message_empty_handler(e, *args, **kwargs):
    # if isinstance(e, MessageException):
    #     return make_response(jsonify(e.message), to_http_status(e.message['status']))
    # else:
    log.error('运行错误 %s' % e, exc_info=True)
    return make_response(jsonify({'status': UserAPIStatus.Ok, 'msg': '成功', 'data': {}}), to_http_status(UserAPIStatus.Ok))
Ejemplo n.º 5
0
def message_handler(e, *args, func_name=None, **kwargs):
    if isinstance(e, MessageException):
        return make_response(jsonify(e.message), to_http_status(e.message['status']))
    else:
        log.error('%s 运行错误 %s' % (func_name, e), exc_info=True)
        return make_response(jsonify(ServerError), to_http_status(ServerError['status']))
Ejemplo n.º 6
0
Archivo: hb.py Proyecto: whitefirer/hb
def create_hb201902(chart_data, node_id, click_time):
    answer = bytes(app.config['HB201902_CODE'], 'utf-8')
    failed_tip = '胜败乃兵家常事,少侠请从头再来'
    tips = {
        '0': '点得我好疼啊~',
        '1': '送分题\n难度:未知',
        '2': '2是第一个素数',
        '16': 'AES的16位key是什么?',
        '37': '答案的关键',
        '73': '谢耳朵最喜欢的数字',
        '2019': '新年快乐~',
        '9102': '2019有你想有的东西',
        '9444732965739290427429': '恭喜你找到了!\n'
    }
    #log.debug('hb201902 tips: %s' % tips)

    tip = ''
    max_try = 30
    try:
        try_cnt = get_hit_count('#'.join(['201902', str(click_time)]))
        log.debug('try_cnt: %d' % try_cnt)
        if try_cnt > max_try:  # 30次
            node_id = '1'
            tip = failed_tip
    except Exception as e:
        log.error('try_cnt: %s' % str(e))
        node_id = '1'
        tip = 'redis stopped'

    cpt = None
    try:
        if node_id not in ['-1', '0', '1']:
            old_secret_key = ('%10.06f' %
                              (click_time + 20190101 + try_cnt - 1)).replace(
                                  '.', '')
            log.debug('Crypt old_secret_key: %s' % old_secret_key)
            cpt = Crypt(old_secret_key)
            try:
                node_id = cpt.decrypt(node_id)
            except Exception as e:
                node_id = '0'

        if tip in [failed_tip, 'redis stopped']:
            try_cnt = 0
            click_time = float('%10.06f' % time.time())
        secret_key = ('%10.06f' % (click_time + 20190101 + try_cnt)).replace(
            '.', '')
        log.debug('Crypt secret_key: %s' % secret_key)
        cpt = Crypt(secret_key)

    except Exception as e:
        log.error('Crypt: %s' % str(e))
        node_id = '1'
        tip = failed_tip

    log.debug("create_hb201902 node_id: %s" % node_id)

    if tip not in [failed_tip, 'redis stopped']:
        tip = tips.get(str(node_id))

    create_tips(chart_data, '剩余步数%s' % (max_try - try_cnt), '-1')
    name = '0'
    if tip:
        tip_secret_key = ('%10.06f' % click_time).replace('.', '')
        tip_cpt = Crypt(tip_secret_key)
        if node_id == '2019':
            name = tip_cpt.encrypt('the old place')
        elif node_id == '9444732965739290427429':  # 2**73+37
            name = tip_cpt.encrypt(base64.b64encode(answer).decode('utf-8'))
    create_tips(chart_data, tip, name)
    log.debug('create_hb201902 tip:%s' % tip)

    if node_id not in ['0', '-1']:
        create_nodes(chart_data, [int(node_id)], 3, cpt)

    if tip in [failed_tip, 'redis stopped']:
        return False, click_time

    return True, click_time
Ejemplo n.º 7
0
        log.warning(f"<{request.remote_addr}> {missingParams}")
        return {"error": missingParams}, 400
    # make sure OS is valid
    targetOS = request.json["os"]
    if targetOS not in ["linux", "windows"]:
        return {
            "error":
            "the only supported agent architectures are linux and windows"
        }, 400
    filename = targetOS + "Installer.zip"
    # check what the latest version is
    response = requests.get(
        "https://github.com/lawndoc/commander/releases/latest/download/version.txt",
        allow_redirects=True)
    if response.status_code != 200:
        log.error("failed to fetch agent version information from GitHub")
        raise CommanderError(
            "failed to fetch agent version information from GitHub")
    version = response.content.decode("utf-8").strip()
    # check if we have the newest installers
    if not path.exists(f"agent/installers/{version}/{filename}"):
        try:
            getLatestAgentInstallers(version)
        except CommanderError as e:
            log.error(e)
            raise e
    log.info(f"<{request.remote_addr}> sending agent installer for {targetOS}")
    return send_from_directory(f"agent/installers/{version}/{filename}",
                               filename=filename), 200