def emergency_rule(request): if request.method == 'GET': header_title, path1, path2 = u"告警规则设置", u"告警管理", u"告警规则" users = User.objects.all() media_list = EmergencyType.objects.all() return my_render('emergency/emer_rules.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = EmergencyRules.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = EmergencyRules.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] emer_content = EMER_CONTENTS time_types = {'1': u'全部', '2': u'工作日', '3': u'周末'} for item in page_data: res = {} res['id'] = item.id res['content'] = emer_content.get(str(item.content), '') res['user'] = '******'.join([user.username for user in item.staff.all()]) res['emergency_time'] = time_types.get(str(item.emergency_time), '') res['media_type'] = item.media_type.name if item.media_type else '' res['status'] = u'启用' if item.status else u'禁用' data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_sudo_list(request): """ list sudo commands alias :param request: :return: """ # 渲染数据 if request.method == 'GET': header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名" return my_render('permManage/perm_sudo_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermSudo.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermSudo.objects.all()[page_start:page_end] rest["iTotalRecords"] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name']=item.name res['commands'] =item.commands res['date_joined'] = item.date_added.strftime("%Y-%m-%d %H:%M:%S") data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def media_list(request): if request.method == "GET": header_title, path1, path2 = u'告警媒介类型', u'告警管理', u'查看告警媒介类型' return my_render('emergency/media_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = EmergencyType.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = EmergencyType.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] for item in page_data: res={} res['id']=item.id res['name']=item.name res['type']= u'电子邮件'if '0' in item.type else u'微信' res['status']= u'启用'if '1'in item.status else u'禁用' res['detail']=item.detail res['comment']=item.comment data.append(res) rest['aaData']=data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_sudo_detail(request): header_title, path1, path2 = u"SUDO别名", u"SUDO别名管理", "SUDO详情" sudo_id = request.GET.get('id') sudo = PermSudo.objects.get(id=int(sudo_id)) sudo_roles = sudo.perm_role.all() sudo_operator_record = Task.objects.filter(role_name=sudo.name).filter(role_uuid=sudo.uuid_id) return my_render('permManage/perm_sudo_detail.html', locals(), request)
def emergency_event(request): if request.method == 'GET': header_title, path1, path2 = u"告警事件", u'告警管理', u'告警事件' return my_render('emergency/emer_event.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = EmergencyEvent.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = EmergencyEvent.objects.all()[page_start:page_end] rest["iTotalRecords"] = len(page_data) data = [] emer_content = EMER_CONTENTS for item in page_data: res = {} res['id'] = item.id res['emer_time'] = item.emer_time.strftime("%Y-%m-%d %H:%M:%S") res['emer_event'] = emer_content.get(str(item.emer_event.content), '') res['emer_user'] = item.emer_user res['emer_id'] = item.id res['emer_info'] = item.emer_info res['emer_result'] = u'已执行' if item.emer_result else u'未执行' res['emer_content_num'] = item.emer_event.content data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_sudo_detail(request): header_title, path1, path2 = u"SUDO别名", u"SUDO别名管理", "SUDO详情" sudo_id = request.GET.get('id') sudo = PermSudo.objects.get(id=int(sudo_id)) sudo_roles = sudo.perm_role.all() sudo_operator_record = Task.objects.filter(role_name=sudo.name).filter( role_uuid=sudo.uuid_id) return my_render('permManage/perm_sudo_detail.html', locals(), request)
def perm_role_edit(request, res, *args): """ edit role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户编辑" res['operator'] = path2 # 渲染数据 role_id = request.GET.get("id") role = PermRole.objects.get(id=role_id) role_pass = CRYPTOR.decrypt(role.password) sudo_all = PermSudo.objects.all() role_sudos = role.sudo.all() sudo_all = PermSudo.objects.all() if request.method == "GET": return my_render('permManage/perm_role_edit.html', locals(), request) if request.method == "POST": # 获取 POST 数据 role_name = request.POST.get("role_name") role_password = request.POST.get("role_password") role_comment = request.POST.get("role_comment") role_sudo_names = request.POST.getlist("sudo_name") role_sudos = [PermSudo.objects.get(id=sudo_id) for sudo_id in role_sudo_names] key_content = request.POST.get("role_key", "") try: if not role: raise ServerError('该系统用户不能存在') if role_name == "root": raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!') if role_password: encrypt_pass = CRYPTOR.encrypt(role_password) role.password = encrypt_pass # 生成随机密码,生成秘钥对 if key_content: try: key_path = gen_keys(key=key_content, key_path_dir=role.key_path) except SSHException: raise ServerError('输入的密钥不合法') logger.debug('Recreate role key: %s' % role.key_path) # 写入数据库 role.name = role_name role.comment = role_comment role.sudo = role_sudos role.save() msg = u"更新系统用户: %s" % role.name res['content'] = msg return HttpResponseRedirect(reverse('role_list')) except ServerError, e: error = e res['flag'] = 'false' res['content'] = e
def perm_rule_list(request): """ list rule page 授权规则列表 """ if request.method == 'GET': header_title, path1, path2 = "授权规则", "规则管理", "查看规则" users = User.objects.all() user_groups = UserGroup.objects.all() assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() roles = PermRole.objects.all() return my_render('permManage/perm_rule_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermRule.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": [] } page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermRule.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name'] = item.name res['user_num'] = len(item.user.all()) res['user_group_num'] = len(item.user_group.all()) res['asset_num'] = len(item.asset.all()) res['asset_group_num'] = len(item.asset_group.all()) res['role_num'] = len(item.role.all()) res['user_names'] = ','.join( [user.username for user in item.user.all()]) res['user_group_names'] = ','.join( [user_group.name for user_group in item.user_group.all()]) res['asset_names'] = ','.join( [asset.name for asset in item.asset.all()]) res['asset_group_names'] = ','.join([ asset_group.name for asset_group in item.asset_group.all() ]) res['role_names'] = ','.join( [role.name for role in item.role.all()]) data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def proxy_list(request): """ 查看proxy """ header_title, path1, path2 = '查看代理', '代理管理', '查看代理' keyword = request.GET.get('search', '') proxy_lists = Proxy.objects.all().order_by('create_time') proxy_id = request.GET.get('id', '') if keyword: proxy_lists = proxy_lists.filter(Q(name__icontains=keyword) | Q(create_time__icontains=keyword)) if proxy_id: proxy_lists = proxy_lists.filter(id=int(proxy_id)) proxy_lists, p, proxys, page_range, current_page, show_first, show_end = pages(proxy_lists, request) return my_render('proxyManage/proxy_list.html', locals(), request)
def perm_rule_list(request): """ list rule page 授权规则列表 """ if request.method == 'GET': header_title, path1, path2 = "授权规则", "规则管理", "查看规则" users = User.objects.all() user_groups = UserGroup.objects.all() assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() roles = PermRole.objects.all() return my_render('permManage/perm_rule_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermRule.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermRule.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name'] = item.name res['user_num'] = len(item.user.all()) res['user_group_num'] = len(item.user_group.all()) res['asset_num'] = len(item.asset.all()) res['asset_group_num'] = len(item.asset_group.all()) res['role_num'] = len(item.role.all()) res['user_names'] = ','.join([user.username for user in item.user.all()]) res['user_group_names'] = ','.join([user_group.name for user_group in item.user_group.all()]) res['asset_names'] = ','.join([asset.name for asset in item.asset.all()]) res['asset_group_names'] = ','.join([asset_group.name for asset_group in item.asset_group.all()]) res['role_names'] = ','.join([role.name for role in item.role.all()]) data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_sudo_list(request): """ list sudo commands alias :param request: :return: """ # 渲染数据 header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名" # 获取所有sudo 命令别名 sudos_list = PermSudo.objects.all() # TODO: 搜索和分页 keyword = request.GET.get('search', '') if keyword: sudos_list = sudos_list.filter(Q(name=keyword)) sudos_list, p, sudos, page_range, current_page, show_first, show_end = pages(sudos_list, request) return my_render('permManage/perm_sudo_list.html', locals(), request)
def perm_role_list(request): """ list role page """ if request.method == 'GET': header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户" sudos = PermSudo.objects.all() # TODO 推送系统用户所需的数据 assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() return my_render('permManage/perm_role_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermRole.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": [] } page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermRole.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name'] = item.name res['sudos'] = ','.join( [sudo.name for sudo in item.sudo.all()]) res['date_joined'] = item.date_added.strftime( "%Y-%m-%d %H:%M:%S") data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_rule_list(request): """ list rule page 授权规则列表 """ # 渲染数据 header_title, path1, path2 = "授权规则", "规则管理", "查看规则" # 获取所有规则 rules_list = PermRule.objects.all() rule_id = request.GET.get('id') # TODO: 搜索和分页 keyword = request.GET.get('search', '') if rule_id: rules_list = rules_list.filter(id=rule_id) if keyword: rules_list = rules_list.filter(Q(name=keyword)) rules_list, p, rules, page_range, current_page, show_first, show_end = pages(rules_list, request) return my_render('permManage/perm_rule_list.html', locals(), request)
def perm_role_list(request): """ list role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户" # 获取所有系统角色 roles_list = PermRole.objects.all() role_id = request.GET.get('id') # TODO: 搜索和分页 keyword = request.GET.get('search', '') if keyword: roles_list = roles_list.filter(Q(name=keyword)) if role_id: roles_list = roles_list.filter(id=role_id) roles_list, p, roles, page_range, current_page, show_first, show_end = pages(roles_list, request) return my_render('permManage/perm_role_list.html', locals(), request)
def perm_sudo_list(request): """ list sudo commands alias :param request: :return: """ # 渲染数据 if request.method == 'GET': header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名" return my_render('permManage/perm_sudo_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermSudo.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": [] } page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermSudo.objects.all()[page_start:page_end] rest["iTotalRecords"] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name'] = item.name res['commands'] = item.commands res['date_joined'] = item.date_added.strftime( "%Y-%m-%d %H:%M:%S") data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
def perm_role_list(request): """ list role page """ if request.method == 'GET': header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户" sudos = PermSudo.objects.all() # TODO 推送系统用户所需的数据 assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() return my_render('permManage/perm_role_list.html', locals(), request) else: try: page_length = int(request.POST.get('length', '5')) total_length = PermRole.objects.all().count() keyword = request.POST.get("search") rest = { "iTotalRecords": 0, # 本次加载记录数量 "iTotalDisplayRecords": total_length, # 总记录数量 "aaData": []} page_start = int(request.POST.get('start', '0')) page_end = page_start + page_length page_data = PermRole.objects.all()[page_start:page_end] rest['iTotalRecords'] = len(page_data) data = [] for item in page_data: res = {} res['id'] = item.id res['name'] = item.name res['sudos'] = ','.join([sudo.name for sudo in item.sudo.all()]) res['date_joined'] = item.date_added.strftime("%Y-%m-%d %H:%M:%S") data.append(res) rest['aaData'] = data return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message)
role = get_object(PermRole, id=int(role_id)) role_info = get_role_info(role_id) # 系统用户推送记录 rules = role_info.get("rules") assets = role_info.get("assets") asset_groups = role_info.get("asset_groups") users = role_info.get("users") user_groups = role_info.get("user_groups") pushed_asset, need_push_asset = get_role_push_host(get_object(PermRole, id=role_id)) # 系统用户在proxy上的操作记录 role_operator_record = Task.objects.filter(role_name=role.name).filter(role_uuid=role.uuid_id) except ServerError, e: logger.error(e) return my_render('permManage/perm_role_detail.html', locals(), request) @require_role('admin') @user_operator_record def perm_role_edit(request, res, *args): """ 编辑系统用户 """ # 渲染数据 res['operator'] = u"编辑系统用户" res['emer_content'] = 6 if request.method == "GET": role_id = request.GET.get("id") role = PermRole.objects.get(id=int(role_id)) if not role:
user_group_obj = rule_obj.user_group.all() asset_obj = rule_obj.asset.all() asset_group_obj = rule_obj.asset_group.all() roles_name = [role.name for role in rule_obj.role.all()] # 渲染数据 roles_name = ','.join(roles_name) rule = rule_obj users = user_obj user_groups = user_group_obj assets = asset_obj asset_groups = asset_group_obj except ServerError, e: logger.warning(e) return my_render('permManage/perm_rule_detail.html', locals(), request) @user_operator_record def perm_rule_add(request, res, *args): """ add rule page 添加授权 """ header_title, path1, path2 = "授权规则", "规则管理", "添加规则" res['operator'] = path2 # 渲染数据, 获取所有 用户,用户组,资产,资产组,用户角色, 用于添加授权规则 users = User.objects.all() user_groups = UserGroup.objects.all() assets = Asset.objects.all() asset_groups = AssetGroup.objects.all()
try: if not proxy_name: raise ServerError('Proxy名不能为空') if Proxy.objects.filter(proxy_name=proxy_name): raise ServerError('Proxy名已存在') create_time = datetime.now() Proxy.objects.create(proxy_name=proxy_name, username=user_name, password=password, url=proxy_url, comment=comment, create_time=create_time) msg = '添加Proxy[%s]成功' % proxy_name res['content'] = msg except ServerError, e: error = e res['flag'] = False res['content'] = error return my_render('proxyManage/proxy_add.html', locals(), request) @require_role('admin') @user_operator_record def proxy_edit(request, res, *args): error = '' msg = '' header_title, path1, path2 = '编辑代理', '代理管理', '编辑代理' res['operator'] = path2 if request.method == 'GET': id = request.GET.get('id', '') proxy = get_object(Proxy, id=id) else: id = int(request.POST.get('proxy_id')) proxy_name = request.POST.get('proxy_name', '')
def perm_role_push(request, res, *args): """ the role push page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户推送" res['operator'] = path2 role_id = request.GET.get('id') asset_ids = request.GET.get('asset_id') role = get_object(PermRole, id=role_id) assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() if asset_ids: need_push_asset = [get_object(Asset, id=asset_id) for asset_id in asset_ids.split(',')] if request.method == "POST": # 获取推荐角色的名称列表 # 计算出需要推送的资产列表 asset_ids = request.POST.getlist("assets") asset_group_ids = request.POST.getlist("asset_groups") assets_obj = [Asset.objects.get(id=asset_id) for asset_id in asset_ids] asset_groups_obj = [AssetGroup.objects.get(id=asset_group_id) for asset_group_id in asset_group_ids] group_assets_obj = [] for asset_group in asset_groups_obj: group_assets_obj.extend(asset_group.asset_set.all()) calc_assets = list(set(assets_obj) | set(group_assets_obj)) push_resource = gen_resource(calc_assets) # 调用Ansible API 进行推送 password_push = True if request.POST.get("use_password") else False key_push = True if request.POST.get("use_publicKey") else False task = MyTask(push_resource) ret = {} # 因为要先建立用户,而push key是在 password也完成的情况下的 可选项 # 1. 以秘钥 方式推送角色 if key_push: ret["pass_push"] = task.add_user(role.name) ret["key_push"] = task.push_key(role.name, os.path.join(role.key_path, 'id_rsa.pub')) # 2. 推送账号密码 <为了安全 系统用户统一使用秘钥进行通信, 不再提供密码方式的推送> # elif password_push: # ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password)) # 3. 推送sudo配置文件 if key_push: sudo_list = set([sudo for sudo in role.sudo.all()]) # set(sudo1, sudo2, sudo3) if sudo_list: ret['sudo'] = task.push_sudo_file([role], sudo_list) logger.debug('推送role结果: %s' % ret) success_asset = {} failed_asset = {} logger.debug(ret) for push_type, result in ret.items(): if result.get('failed'): for hostname, info in result.get('failed').items(): if hostname in failed_asset.keys(): if info in failed_asset.get(hostname): failed_asset[hostname] += info else: failed_asset[hostname] = info for push_type, result in ret.items(): if result.get('ok'): for hostname, info in result.get('ok').items(): if hostname in failed_asset.keys(): continue elif hostname in success_asset.keys(): if str(info) in success_asset.get(hostname, ''): success_asset[hostname] += str(info) else: success_asset[hostname] = str(info) # 推送成功 回写push表 for asset in calc_assets: push_check = PermPush.objects.filter(role=role, asset=asset) if push_check: func = push_check.update else: def func(**kwargs): PermPush(**kwargs).save() if failed_asset.get(asset.name): func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=False, result=failed_asset.get(asset.name)) else: func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=True) if not failed_asset: msg = u'系统用户 %s 推送成功[ %s ]' % (role.name, ','.join(success_asset.keys())) res['content'] = msg else: error = u'系统用户 %s 推送失败 [ %s ], 推送成功 [ %s ] 进入系统用户详情,查看失败原因' % (role.name, ','.join(failed_asset.keys()), ','.join(success_asset.keys())) res['flag'] = 'false' res['content'] = error return my_render('permManage/perm_role_push.html', locals(), request)
# 系统用户推送记录 rules = role_info.get("rules") assets = role_info.get("assets") asset_groups = role_info.get("asset_groups") users = role_info.get("users") user_groups = role_info.get("user_groups") pushed_asset, need_push_asset = get_role_push_host( get_object(PermRole, id=role_id)) # 系统用户在proxy上的操作记录 role_operator_record = Task.objects.filter( role_name=role.name).filter(role_uuid=role.uuid_id) except ServerError, e: logger.error(e) return my_render('permManage/perm_role_detail.html', locals(), request) @require_role('admin') @user_operator_record def perm_role_edit(request, res, *args): """ 编辑系统用户 """ # 渲染数据 res['operator'] = u"编辑系统用户" res['emer_content'] = 6 if request.method == "GET": role_id = request.GET.get("id") role = PermRole.objects.get(id=int(role_id)) if not role: