def send_email(email_config, email_title, email_to, email_msg): """ 发送邮件 """ rest = {'msgCode': 0, 'msgError': ''} # msgCode: 0:成功 1:失败 message = MIMEText(email_msg, 'plain', 'utf-8') message['Subject'] = Header(email_title) message['From'] = email_config.email_username emali_list = ','.join(email_to) message['To'] = emali_list server = smtplib.SMTP() if email_config.email_use_ssl: server = smtplib.SMTP_SSL() try: server.connect(email_config.smtp_server, email_config.smtp_server_port) if email_config.email_use_tls and email_config.email_use_ssl is not True: server.starttls() logger.info(u'%s: password %s' % (email_config.name, email_config.email_password)) server.login(email_config.email_username, CRYPTOR.decrypt(email_config.email_password)) server.sendmail(email_config.email_username, email_to, message.as_string()) except Exception as e: rest['msgCode'] = 1 rest['msgError'] = e logger.error(e) finally: server.quit() return rest
def perm_role_detail(request): """ the role detail page the role_info data like: {'asset_groups': [], 'assets': [<Asset: 192.168.10.148>], 'rules': [<PermRule: PermRule object>], '': [], '': [<User: user1>]} """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户详情" try: if request.method == "GET": role_id = request.GET.get("id") if not role_id: raise ServerError("not role id") 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)
def send_email(email_config, email_title, email_to, email_msg): """ 发送邮件 """ rest = {'msgCode': 0, 'msgError': ''} # msgCode: 0:成功 1:失败 message = MIMEText(email_msg, 'plain', 'utf-8') message['Subject'] = Header(email_title) message['From'] = email_config.email_username emali_list = ','.join(email_to) message['To'] = emali_list server = smtplib.SMTP() if email_config.email_use_ssl: server = smtplib.SMTP_SSL() try: server.connect(email_config.smtp_server, email_config.smtp_server_port) if email_config.email_use_tls and email_config.email_use_ssl is not True: server.starttls() logger.info(u'%s: password %s'%(email_config.name, email_config.email_password)) server.login(email_config.email_username, CRYPTOR.decrypt(email_config.email_password)) server.sendmail(email_config.email_username, email_to, message.as_string()) except Exception as e: rest['msgCode'] = 1 rest['msgError'] = e logger.error(e) finally: server.quit() return rest
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 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 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_role_detail(request): """ the role detail page the role_info data like: {'asset_groups': [], 'assets': [<Asset: 192.168.10.148>], 'rules': [<PermRule: PermRule object>], '': [], '': [<User: user1>]} """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户详情" try: if request.method == "GET": role_id = request.GET.get("id") if not role_id: raise ServerError("not role id") 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)
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 role_proxy_operator(user_name, obj_name, data, proxy=None, obj_uuid='all', action='add'): """ 保存,更新, 删除数据,并把操作结果保存到Task表中 obj_name: PermRole, PermSudo """ result = res_info = msg_name = '' g_lock = threading.Lock() # 线程锁 if obj_name == 'PermRole': msg_name = u'系统用户' elif obj_name == 'PermSudo': msg_name = u'SUDO别名' g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid) try: g_lock.acquire() # 在每个proxy上(add/update/delete) role/sudo,并返回结果 api = APIRequest(g_url, proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) pdata = json.loads(data) res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'update': result, codes = api.req_put(data) pdata = json.loads(data) res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'delete': result, codes = api.req_del(data) pdata = json.loads(data) res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) logger.info('role_proxy_%s:%s'%(action, result['messege'])) # 生成唯一的事件名称,用于从数据库中查询执行结果 if 'name' not in json.dumps(data): raise ValueError('role_proxy_operator: data["name"]不存在') task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex # 将事件添加到消息队列中 task_queue.put({'server': task_name, 'username': user_name}) # 将执行结果保存到数据库中 role_task = Task() role_task.task_name = task_name role_task.proxy_name = proxy.proxy_name role_task.role_name = json.loads(data)['name'] role_task.username = user_name role_task.status = 'complete' role_task.content = res_info role_task.url = g_url role_task.start_time = datetime.datetime.now() role_task.action = action role_task.role_uuid = obj_uuid role_task.role_data = data role_task.result = result['messege'] role_task.save() except Exception as e: logger.error("[role_proxy_operator] %s"%e) finally: g_lock.release() return result
def run(self): while True: try: do_func, args, kwargs = self.work_queue.get(block=False) # 任务异步出队,Queue内部实现了同步机制 do_func(*args, **kwargs) self.work_queue.task_done() # 通知系统任务完成 except Exception as e: logger.error(e) break
def req_post(self, data=None, **kwargs): try: req = requests.post(self.url, data=data, headers=self.header, **kwargs) codes = req.status_code msg = req.json() except Exception, e: logger.error(traceback.format_exc()) codes = 500 msg = e.message
def req_get(self): try: req = requests.get(self.url, headers=self.header) msg = req.json() codes = req.status_code except Exception as e: logger.error(e) codes = 500 msg = e.message return msg, codes
def run(self): while True: try: do_func, args, kwargs = self.work_queue.get( block=False) # 任务异步出队,Queue内部实现了同步机制 do_func(*args, **kwargs) self.work_queue.task_done() # 通知系统任务完成 except Exception as e: logger.error(e) break
def execute_thread_tasks(proxy_list, thread_num, func, *args, **kwargs): """ 多个任务并发执行 """ try: work_manager = WorkManager(proxy_list, thread_num) work_manager.init_work_queue(func, *args, **kwargs) work_manager.init_thread_pool() except Exception as e: logger.error("[execute_thread_tasks] %s" % e)
def req_put(self, data): try: req = requests.put(self.url, headers=self.header, data=data) codes = req.status_code msg = req.json() except Exception as e: logger.error(e) codes = 500 msg = e.message return msg, codes
def execute_thread_tasks(proxy_list, thread_num, func, *args, **kwargs): """ 多个任务并发执行 """ try: work_manager = WorkManager(proxy_list, thread_num) work_manager.init_work_queue(func, *args, **kwargs) work_manager.init_thread_pool() except Exception as e: logger.error("[execute_thread_tasks] %s"%e)
def req_del(self, data): try: req = requests.delete(self.url, headers=self.header, data=data) codes = req.status_code msg = req.json() logger.debug("msg:%s status_codes:%s" % (msg, codes)) except Exception as e: logger.error(e) codes = 500 msg = e.message return msg, codes
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 get_one_or_all(obj_name, proxy, obj_uuid='all'): """ 获取所有的对象或者一个id对应的对象 """ obj_list = [] try: api = APIRequest('{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_get() obj_list = result['messege'] except Exception as e: logger.error(e) return obj_list
def perm_role_retry(request, res): """ 第一次添加或者更新失败后,再次在proxy上添加或者更新系统用户/SUDO action: 添加 or 编辑 character: 标记系统用户 or SUDO """ response = {'success': True, 'message': ''} res['emer_content'] = 6 if request.method == 'POST': tk_id = request.POST.get('id') action = request.POST.get('action') character = request.POST.get('character') if '' or None in [tk_id, action]: response['success'] = False response['message'] = '必要参数为空' return HttpResponse(json.dumps(response), content_type='application/json') try: tk_event = Task.objects.get(id=int(tk_id)) if character == 'role': obj_name = 'PermRole' msg_info = u'系统用户' error_role = PermRole.objects.get(uuid_id=tk_event.role_uuid, name=tk_event.role_name) else: obj_name = 'PermSudo' msg_info = u'SUDO' error_role = PermSudo.objects.get(uuid_id=tk_event.role_uuid, name=tk_event.role_name) operate = u'添加' if action == 'add' else u'编辑' error_proxy = Proxy.objects.get(proxy_name=tk_event.proxy_name) role_data = tk_event.role_data res['operator'] = u"重新在proxy上{}{}".format(operate,msg_info) info = save_or_delete(obj_name, role_data, error_proxy, error_role.uuid_id, action) if info == 'success': tk_event.result = info tk_event.save() res['emer_status'] = u'重新在[{0}]上{1}{2}[{3}]成功'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) res['content'] = u'重新在[{0}]上{1}{2}[{3}]成功'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) else: res['flag'] = 'false' res['emer_status'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) res['content'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) response['success'] = False response['message'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) except Exception as e: res['flag'] = 'false' errorMsg = u'重新在[{0}]上{1}{2}[{3}]失败'.format(error_proxy.proxy_name,operate, msg_info, error_role.name) res['content'] = errorMsg res['emer_status'] = errorMsg response['success'] = False response['message'] = u'重新在[{0}]上{1}{2}[{3}]失败:{4}'.format(error_proxy.proxy_name,operate, msg_info, error_role.name,e) logger.error(e) return HttpResponse(json.dumps(response), content_type='application/json')
def get_one_or_all(obj_name, proxy, obj_uuid='all'): """ 获取所有的对象或者一个id对应的对象 """ obj_list = [] try: api = APIRequest( '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_get() obj_list = result['messege'] except Exception as e: logger.error(e) return obj_list
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_role_push(request, *args): """ 推送系统用户 """ if request.method == 'GET': try: rest = {} role_id = request.GET.get('id') role = get_object(PermRole, id=int(role_id)) rest['Id'] = role.id rest['role_name'] = role.name return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e) else: response = {'success': False, 'error': ''} try: role_id = request.GET.get('id') role = get_object(PermRole, id=int(role_id)) 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)) proxy_list = Proxy.objects.all() execute_thread_tasks(proxy_list, THREAD_NUMBERS, push_role_to_asset, calc_assets, role, request.user.username) response['success'] = True response['error'] = 'running ...' except Exception as e: response['error'] = e.message logger.error(e.message) return HttpResponse(json.dumps(response), content_type='application/json')
def download_key(request, res): res['operator'] = '下载秘钥' res['content'] = '下载系统用户秘钥成功' if request.method == 'GET': try: role_id = request.GET.get('id', '') if not role_id: raise ValueError('下载秘钥失败:ID为空 ') role = PermRole.objects.get(id=int(role_id)) key_data = json.loads(role.key_content).get('private_key') response = HttpResponse(key_data, content_type='application/x-x509-ca-cert') response['Content-Disposition'] = 'attachment; filename="%s.pem"'%role.name return response except Exception as e: res['flag'] = 'false' res['content'] = '下载秘钥失败:%s'%e.message logger.error(e) return HttpResponse(e)
def download_key(request, res): res['operator'] = '下载秘钥' res['content'] = '下载系统用户秘钥成功' if request.method == 'GET': try: role_id = request.GET.get('id', '') if not role_id: raise ValueError('下载秘钥失败:ID为空 ') role = PermRole.objects.get(id=int(role_id)) key_data = json.loads(role.key_content).get('private_key') response = HttpResponse(key_data, content_type='application/x-x509-ca-cert') response[ 'Content-Disposition'] = 'attachment; filename="%s.pem"' % role.name return response except Exception as e: res['flag'] = 'false' res['content'] = '下载秘钥失败:%s' % e.message logger.error(e) return HttpResponse(e)
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 save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'): """ 保存,更新, 删除数据 obj_name: 'PermRole' obj_uuid: role.uuid_id """ info = '' try: api = APIRequest('{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) elif action == 'update': result, codes = api.req_put(data) elif action == 'delete': result, codes = api.req_del(data) if result is not None: info = result['messege'] except Exception as e: info = 'error' logger.error("[save_or_delete] %s"%e) return info
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)
def perm_role_push(request, *args): """ 推送系统用户 """ if request.method == 'GET': try: rest = {} role_id = request.GET.get('id') role = get_object(PermRole, id=int(role_id)) rest['Id'] = role.id rest['role_name'] = role.name return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e) else: response = {'success': False, 'error': ''} try: role_id = request.GET.get('id') role = get_object(PermRole, id=int(role_id)) 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)) proxy_list = Proxy.objects.all() execute_thread_tasks(proxy_list, THREAD_NUMBERS, push_role_to_asset, calc_assets, role, request.user.username) response['success'] = True response['error'] = 'running ...' except Exception as e: response['error'] = e.message logger.error(e.message) return HttpResponse(json.dumps(response), content_type='application/json')
def save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'): """ 保存,更新, 删除数据 obj_name: 'PermRole' obj_uuid: role.uuid_id """ info = '' try: api = APIRequest( '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) elif action == 'update': result, codes = api.req_put(data) elif action == 'delete': result, codes = api.req_del(data) if result is not None: info = result['messege'] except Exception as e: info = 'error' logger.error("[save_or_delete] %s" % e) return info
def media_edit(request, res): res['operator'] = u'编辑告警媒介' if request.method == 'GET': try: media_id = request.GET.get('id', '') media_info = EmergencyType.objects.get(id=int(media_id)) rest = {} rest['Id'] = media_info.id rest['name'] = media_info.name rest['type'] = media_info.type rest['status'] = media_info.status rest['smtp_server'] = media_info.smtp_server rest['smtp_server_port'] = media_info.smtp_server_port rest['email_username'] = media_info.email_username email_psswd = CRYPTOR.decrypt(media_info.email_password) if media_info.email_password else '' # 将密码解密后在传到前端 rest['email_password'] = email_psswd rest['email_use_tls'] = media_info.email_use_tls rest['email_use_ssl'] = media_info.email_use_ssl rest['corpid'] = media_info.corpid rest['corpsecret'] = media_info.corpsecret rest['comment'] = media_info.comment return HttpResponse(json.dumps(rest), content_type='application/json') except Exception as e: logger.error(e.message) return HttpResponse(e.message) else: response = {'success': False, 'error': ''} m_id = request.GET.get('id', '') media = EmergencyType.objects.get(id=int(m_id)) media_name = request.POST.get('media_name', '') media_type = request.POST.get('media_type', '') try: old_name=media.name if old_name==media_name: if EmergencyType.objects.filter(name=media_name).count()>1: raise ServerError(u'名称[%s]已存在'% media_name) else: if EmergencyType.objects.filter(name=media_name).count()>0: raise ServerError(u"名称[%s]已存在"% media_name) if media_type == '0': smtp_host = request.POST.get('smtp_host', '') smtp_host_port = int(request.POST.get('smtp_host_port', 587)) email_user = request.POST.get('email_user', '') email_user_password = request.POST.get('email_user_password', '') encrypt_password = CRYPTOR.encrypt(email_user_password) connect_security = request.POST.getlist('connection', []) status = request.POST.get('extra', '0') comment = request.POST.get('comment', '') is_use_tls = True if '1' in connect_security else 0 is_use_ssl = True if '0' in connect_security else 0 media_detail = u"SMTP服务器:{0} SMTP电邮:{1}".format(smtp_host, email_user) if '' in [media_name, smtp_host, smtp_host_port, email_user, email_user_password]: raise ServerError(u'名称不能为空') media.name = media_name media.type = media_type media.smtp_server = smtp_host media.smtp_server_port = smtp_host_port media.status = status media.email_username = email_user media.email_password = encrypt_password media.email_use_ssl = is_use_ssl media.email_use_tls = is_use_tls media.detail = media_detail media.comment = comment media.save() res['content'] = u'修改告警媒介[%s]成功' % media_name response['success'] = True elif media_type == '1': corpid = request.POST.get('corpid', '') corpsecret = request.POST.get('corpsecret', '') status = request.POST.get('extra', '0') comment = request.POST.get('comment', '') media_detail = u'CorpID:%s'%corpid if '' in [media_name, corpid, corpsecret]: raise ServerError(u'必要参数为空,请从新填写!') media.name = media_name media.type = media_type media.status = status media.corpid = corpid media.detail = media_detail media.corpsecret = corpsecret media.comment = comment media.save() res['content'] = u'修改告警媒介[%s]成功'%media.name response['success'] = True except Exception as e: logger.error(e) res['flag'] = 'false' response['error'] =res['content'] = u'修改告警媒介失败:%s'%e.message return HttpResponse(json.dumps(response), content_type='application/json')
def role_proxy_operator(user_name, obj_name, data, proxy=None, obj_uuid='all', action='add'): """ 保存,更新, 删除数据,并把操作结果保存到Task表中 obj_name: PermRole, PermSudo """ result = res_info = msg_name = '' g_lock = threading.Lock() # 线程锁 if obj_name == 'PermRole': msg_name = u'系统用户' elif obj_name == 'PermSudo': msg_name = u'SUDO别名' g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid) try: g_lock.acquire() # 在每个proxy上(add/update/delete) role/sudo,并返回结果 api = APIRequest(g_url, proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) pdata = json.loads(data) res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'update': result, codes = api.req_put(data) pdata = json.loads(data) res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'delete': result, codes = api.req_del(data) pdata = json.loads(data) res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) logger.info('role_proxy_%s:%s' % (action, result['messege'])) # 生成唯一的事件名称,用于从数据库中查询执行结果 if 'name' not in json.dumps(data): raise ValueError('role_proxy_operator: data["name"]不存在') task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex # 将事件添加到消息队列中 task_queue.put({'server': task_name, 'username': user_name}) # 将执行结果保存到数据库中 role_task = Task() role_task.task_name = task_name role_task.proxy_name = proxy.proxy_name role_task.role_name = json.loads(data)['name'] role_task.username = user_name role_task.status = 'complete' role_task.content = res_info role_task.url = g_url role_task.start_time = datetime.datetime.now() role_task.action = action role_task.role_uuid = obj_uuid role_task.role_data = data role_task.result = result['messege'] role_task.save() except Exception as e: logger.error("[role_proxy_operator] %s" % e) finally: g_lock.release() return result
def perm_rule_edit(request, res, *args): """ edit rule page """ res['operator'] = "编辑授权规则" res['emer_content'] = 6 if request.method == 'GET': try: rule_id = request.GET.get("id") rule = get_object(PermRule, id=int(rule_id)) if rule: rest = {} rest['Id'] = rule.id rest['name'] = rule.name rest['comment'] = rule.comment rest['asset'] = ','.join( [str(item.id) for item in rule.asset.all()]) rest['asset_group'] = ','.join( str(item.id) for item in rule.asset_group.all()) rest['user'] = '******'.join( str(item.id) for item in rule.user.all()) rest['user_group'] = ','.join( str(item.id) for item in rule.user_group.all()) rest['role'] = ','.join( str(item.id) for item in rule.role.all()) return HttpResponse(json.dumps(rest), content_type='application/json') else: return HttpResponse(u'授权规则不存在') except Exception as e: logger.error(e) else: response = {'success': False, 'error': ''} rule_id = request.GET.get("id") rule = get_object(PermRule, id=int(rule_id)) rule_name_old = rule.name rule_name = request.POST.get('name') rule_comment = request.POST.get("comment") users_select = request.POST.getlist('user', []) user_groups_select = request.POST.getlist('user_group', []) assets_select = request.POST.getlist('asset', []) asset_groups_select = request.POST.getlist('asset_group', []) roles_select = request.POST.getlist('role', []) try: if not rule_name or not roles_select: raise ServerError(u'系统用户和关联系统用户不能为空') if rule_name_old == rule_name: if len(PermRule.objects.filter(name=rule_name)) > 1: raise ServerError(u'授权规则名称[%s]已存在' % rule_name) else: if len(PermRule.objects.filter(name=rule_name)) > 0: raise ServerError(u'授权规则名称[%s]已存在' % rule_name) assets_obj = [ Asset.objects.get(id=asset_id) for asset_id in assets_select ] asset_groups_obj = [ AssetGroup.objects.get(id=group_id) for group_id in asset_groups_select ] group_assets_obj = [] for asset_group in asset_groups_obj: group_assets_obj.extend(list(asset_group.asset_set.all())) calc_assets = set(group_assets_obj) | set( assets_obj) # 授权资产和资产组包含的资产 # 获取需要授权的用户列表 users_obj = [ User.objects.get(id=user_id) for user_id in users_select ] user_groups_obj = [ UserGroup.objects.get(id=group_id) for group_id in user_groups_select ] # 获取授予的角色列表 roles_obj = [ PermRole.objects.get(id=role_id) for role_id in roles_select ] need_push_asset = set() for role in roles_obj: asset_no_push = get_role_push_host( role=role)[1] # 获取某角色已经推送的资产 need_push_asset.update(set(calc_assets) & set(asset_no_push)) if need_push_asset: raise ServerError( u'没有推送系统用户 %s 的主机 %s' % (role.name, ','.join( [asset.name for asset in need_push_asset]))) # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) rule.user = users_obj rule.user_group = user_groups_obj rule.asset = assets_obj rule.asset_group = asset_groups_obj rule.role = roles_obj rule.name = rule_name rule.comment = rule_comment rule.save() res['content'] = u"编辑授权规则[%s]成功" % rule_name_old res['emer_status'] = u"编辑授权规则[%s]成功" % rule_name_old response['success'] = True except Exception, e: res['flag'] = 'false' res['content'] = e.message res['emer_status'] = response['error'] = u"编辑授权规则失败:%s" % e.message return HttpResponse(json.dumps(response), content_type='application/json')
def perm_role_retry(request, res): """ 第一次添加或者更新失败后,再次在proxy上添加或者更新系统用户/SUDO action: 添加 or 编辑 character: 标记系统用户 or SUDO """ response = {'success': True, 'message': ''} res['emer_content'] = 6 if request.method == 'POST': tk_id = request.POST.get('id') action = request.POST.get('action') character = request.POST.get('character') if '' or None in [tk_id, action]: response['success'] = False response['message'] = '必要参数为空' return HttpResponse(json.dumps(response), content_type='application/json') try: tk_event = Task.objects.get(id=int(tk_id)) if character == 'role': obj_name = 'PermRole' msg_info = u'系统用户' error_role = PermRole.objects.get(uuid_id=tk_event.role_uuid, name=tk_event.role_name) else: obj_name = 'PermSudo' msg_info = u'SUDO' error_role = PermSudo.objects.get(uuid_id=tk_event.role_uuid, name=tk_event.role_name) operate = u'添加' if action == 'add' else u'编辑' error_proxy = Proxy.objects.get(proxy_name=tk_event.proxy_name) role_data = tk_event.role_data res['operator'] = u"重新在proxy上{}{}".format(operate, msg_info) info = save_or_delete(obj_name, role_data, error_proxy, error_role.uuid_id, action) if info == 'success': tk_event.result = info tk_event.save() res['emer_status'] = u'重新在[{0}]上{1}{2}[{3}]成功'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) res['content'] = u'重新在[{0}]上{1}{2}[{3}]成功'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) else: res['flag'] = 'false' res['emer_status'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) res['content'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) response['success'] = False response['message'] = u'重新在[{0}]上{1}{2}[{3}]失败'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) except Exception as e: res['flag'] = 'false' errorMsg = u'重新在[{0}]上{1}{2}[{3}]失败'.format( error_proxy.proxy_name, operate, msg_info, error_role.name) res['content'] = errorMsg res['emer_status'] = errorMsg response['success'] = False response['message'] = u'重新在[{0}]上{1}{2}[{3}]失败:{4}'.format( error_proxy.proxy_name, operate, msg_info, error_role.name, e) logger.error(e) return HttpResponse(json.dumps(response), content_type='application/json')
def perm_rule_edit(request, res, *args): """ edit rule page """ res['operator'] = "编辑授权规则" res['emer_content'] = 6 if request.method == 'GET': try: rule_id = request.GET.get("id") rule = get_object(PermRule, id=int(rule_id)) if rule: rest = {} rest['Id'] = rule.id rest['name'] = rule.name rest['comment'] = rule.comment rest['asset'] = ','.join([str(item.id) for item in rule.asset.all()]) rest['asset_group'] = ','.join(str(item.id) for item in rule.asset_group.all()) rest['user'] = '******'.join(str(item.id) for item in rule.user.all()) rest['user_group'] = ','.join(str(item.id) for item in rule.user_group.all()) rest['role'] = ','.join(str(item.id) for item in rule.role.all()) return HttpResponse(json.dumps(rest), content_type='application/json') else: return HttpResponse(u'授权规则不存在') except Exception as e: logger.error(e) else: response = {'success': False, 'error': ''} rule_id = request.GET.get("id") rule = get_object(PermRule, id=int(rule_id)) rule_name_old = rule.name rule_name = request.POST.get('name') rule_comment = request.POST.get("comment") users_select = request.POST.getlist('user', []) user_groups_select = request.POST.getlist('user_group', []) assets_select = request.POST.getlist('asset', []) asset_groups_select = request.POST.getlist('asset_group', []) roles_select = request.POST.getlist('role', []) try: if not rule_name or not roles_select: raise ServerError(u'系统用户和关联系统用户不能为空') if rule_name_old == rule_name: if len(PermRule.objects.filter(name=rule_name)) > 1: raise ServerError(u'授权规则名称[%s]已存在'%rule_name) else: if len(PermRule.objects.filter(name=rule_name)) > 0: raise ServerError(u'授权规则名称[%s]已存在'%rule_name) assets_obj = [Asset.objects.get(id=asset_id) for asset_id in assets_select] asset_groups_obj = [AssetGroup.objects.get(id=group_id) for group_id in asset_groups_select] group_assets_obj = [] for asset_group in asset_groups_obj: group_assets_obj.extend(list(asset_group.asset_set.all())) calc_assets = set(group_assets_obj) | set(assets_obj) # 授权资产和资产组包含的资产 # 获取需要授权的用户列表 users_obj = [User.objects.get(id=user_id) for user_id in users_select] user_groups_obj = [UserGroup.objects.get(id=group_id) for group_id in user_groups_select] # 获取授予的角色列表 roles_obj = [PermRole.objects.get(id=role_id) for role_id in roles_select] need_push_asset = set() for role in roles_obj: asset_no_push = get_role_push_host(role=role)[1] # 获取某角色已经推送的资产 need_push_asset.update(set(calc_assets) & set(asset_no_push)) if need_push_asset: raise ServerError(u'没有推送系统用户 %s 的主机 %s' % (role.name, ','.join([asset.name for asset in need_push_asset]))) # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) rule.user = users_obj rule.user_group = user_groups_obj rule.asset = assets_obj rule.asset_group = asset_groups_obj rule.role = roles_obj rule.name = rule_name rule.comment = rule_comment rule.save() res['content'] = u"编辑授权规则[%s]成功" % rule_name_old res['emer_status'] = u"编辑授权规则[%s]成功" % rule_name_old response['success'] = True except Exception, e: res['flag'] = 'false' res['content'] = e.message res['emer_status'] = response['error'] = u"编辑授权规则失败:%s"%e.message return HttpResponse(json.dumps(response), content_type='application/json')