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=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)) except ServerError, e: logger.warning(e)
def perm_role_delete(request): """ delete role page """ if request.method == "POST": # 获取参数删除的role对象 role_id = request.POST.get("id") role = get_object(PermRole, id=role_id) role_key = role.key_path # 删除推送到主机上的role recycle_assets = [push.asset for push in role.perm_push.all() if push.success] logger.debug(u"delete role %s - delete_assets: %s" % (role.name, recycle_assets)) if recycle_assets: recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) msg = task.del_user(get_object(PermRole, id=role_id).name) logger.info(u"delete role %s - execute delete user: %s" % (role.name, msg)) # TODO: 判断返回结果,处理异常 # 删除存储的秘钥,以及目录 key_files = os.listdir(role_key) for key_file in key_files: os.remove(os.path.join(role_key, key_file)) os.rmdir(role_key) logger.info(u"delete role %s - delete role key directory: %s" % (role.name, role_key)) # 数据库里删除记录 TODO: 判断返回结果,处理异常 role.delete() return HttpResponse(u"删除系统用户: %s" % role.name) else: return HttpResponse(u"不支持该操作")
def group_add_user(group, user_id=None, username=None): """ 用户组中添加用户 :param group: :param user_id: :param username: :return: """ if user_id: user = get_object(User, id=user_id) else: user = get_object(User, name=username) if user: group.user_set.add(user)
def reset_password(request): uuid_r = request.GET.get('uuid', '') timestamp = request.GET.get('timestamp', '') hash_encode = request.GET.get('hash', '') action = '/juser/password/reset/?uuid=%s×tamp=%s&hash=%s' % (uuid_r, timestamp, hash_encode) if hash_encode == PyCrypt.md5_crypt(uuid_r + timestamp + KEY): if int(time.time()) - int(timestamp) > 600: return http_error(request, u'链接已超时') else: return HttpResponse('hash校验失败') if request.method == 'POST': password = request.POST.get('password') password_confirm = request.POST.get('password_confirm') print password, password_confirm if password != password_confirm: return HttpResponse('密码不匹配') else: user = get_object(User, uuid=uuid_r) if user: user.password = PyCrypt.md5_crypt(password) user.save() return http_success(request, u'密码重设成功') else: return HttpResponse('用户不存在') else: return render_to_response('juser/reset_password.html', locals()) return http_error(request, u'错误请求')
def db_update_user(**kwargs): """ 在数据库更新用户信息 :param kwargs: :return: """ group_post = kwargs.pop('groups') admin_groups_post = kwargs.pop('admin_groups') user_id = kwargs.pop('user_id') user = User.objects.filter(id=user_id) if user: user_get = user.first() password = kwargs.pop('password') user.update(**kwargs) if password.strip(): user_get.set_password(password) user_get.save() else: return None group_select = [] if group_post: for group_id in group_post: user_group = UserGroup.objects.filter(id=group_id) group_select.extend(user_group) user_get.group = group_select if admin_groups_post != '': user_get.admingroup_set.all().delete() for group_id in admin_groups_post: group = get_object(UserGroup, id=group_id) AdminGroup(user=user, group=group).save()
def perm_sudo_add(request): """ list sudo commands alias :param request: :return: """ # 渲染数据 header_title, path1, path2 = "Sudo命令", "别名管理", "添加别名" if request.method == "POST": # 获取参数: name, comment name = request.POST.get("sudo_name").strip().upper() comment = request.POST.get("sudo_comment").strip() commands = request.POST.get("sudo_commands").strip() pattern = re.compile(r'[ \n,\r]') commands = ', '.join(list_drop_str(pattern.split(commands), u'')) logger.debug(u'添加sudo %s: %s' % (name, commands)) if get_object(PermSudo, name=name): error = 'Sudo别名 %s已经存在' % name else: sudo = PermSudo(name=name.strip(), comment=comment, commands=commands) sudo.save() msg = u"添加Sudo命令别名: %s" % name # 渲染数据 return my_render('jperm/perm_sudo_add.html', locals(), request)
def perm_role_delete(request): """ delete role page """ if request.method == "GET": try: # 获取参数删除的role对象 role_id = request.GET.get("id") role = get_object(PermRole, id=role_id) if not role: logger.warning(u"Delete Role: role_id %s not exist" % role_id) raise ServerError(u"role_id %s 无数据记录" % role_id) # 删除推送到主机上的role filter_type = request.GET.get("filter_type") print filter_type if filter_type: if filter_type == "recycle_assets": recycle_assets = [push.asset for push in role.perm_push.all() if push.success] print recycle_assets recycle_assets_ip = ','.join([asset.ip for asset in recycle_assets]) return HttpResponse(recycle_assets_ip) else: return HttpResponse("no such filter_type: %s" % filter_type) else: return HttpResponse("filter_type: ?") except ServerError, e: return HttpResponse(e)
def perm_sudo_add(request): """ list sudo commands alias :param request: :return: """ # 渲染数据 header_title, path1, path2 = "Sudo命令", "别名管理", "添加别名" try: if request.method == "POST": # 获取参数: name, comment name = request.POST.get("sudo_name").strip().upper() comment = request.POST.get("sudo_comment").strip() commands = request.POST.get("sudo_commands").strip() if not name or not commands: raise ServerError(u"sudo name 和 commands是必填项!") pattern = re.compile(r'[\n,\r]') deal_space_commands = list_drop_str(pattern.split(commands), u'') deal_all_commands = map(trans_all, deal_space_commands) commands = ', '.join(deal_all_commands) logger.debug(u'添加sudo %s: %s' % (name, commands)) if get_object(PermSudo, name=name): error = 'Sudo别名 %s已经存在' % name else: sudo = PermSudo(name=name.strip(), comment=comment, commands=commands) sudo.save() msg = u"添加Sudo命令别名: %s" % name except ServerError, e: error = e
def search(self, str_r=''): gid_pattern = re.compile(r'^g\d+$') # 获取用户授权的所有主机信息 if not self.user_perm: self.user_perm = get_group_user_perm(self.user) user_asset_all = self.user_perm.get('asset').keys() # 搜索结果保存 user_asset_search = [] if str_r: # 资产组组id匹配 if gid_pattern.match(str_r): gid = int(str_r.lstrip('g')) # 获取资产组包含的资产 user_asset_search = get_object(AssetGroup, id=gid).asset_set.all() else: # 匹配 ip, hostname, 备注 for asset in user_asset_all: if str_r in asset.ip or str_r in str(asset.hostname) or str_r in str(asset.comment): user_asset_search.append(asset) else: # 如果没有输入就展现所有 user_asset_search = user_asset_all self.search_result = dict(zip(range(len(user_asset_search)), user_asset_search)) color_print('[%-3s] %-12s %-15s %-5s %-10s %s' % ('ID', '主机名', 'IP', '端口', '系统用户', '备注'), 'title') for index, asset in self.search_result.items(): # 获取该资产信息 asset_info = get_asset_info(asset) # 获取该资产包含的角色 role = [str(role.name) for role in self.user_perm.get('asset').get(asset).get('role')] print '[%-3s] %-15s %-15s %-5s %-10s %s' % (index, asset.hostname, asset.ip, asset_info.get('port'), role, asset.comment) print
def db_del_user(username): """ 从数据库删除用户 :param username: :return: """ user = get_object(User, username=username) if user: user.delete()
def perm_role_add(request): """ add role page """ # 渲染数据 header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户" sudos = PermSudo.objects.all() if request.method == "POST": # 获取参数: name, comment name = request.POST.get("role_name", "").strip() comment = request.POST.get("role_comment", "") password = request.POST.get("role_password", "") key_content = request.POST.get("role_key", "") sudo_ids = request.POST.getlist('sudo_name') try: if get_object(PermRole, name=name): raise ServerError(u'已经存在该用户 %s' % name) if name == "root": raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!') default = get_object(Setting, name='default') if len(password) > 64: raise ServerError(u'密码长度不能超过64位!') if password: encrypt_pass = CRYPTOR.encrypt(password) else: encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20)) # 生成随机密码,生成秘钥对 sudos_obj = [get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids] if key_content: try: key_path = gen_keys(key=key_content) except SSHException, e: raise ServerError(e) else: key_path = gen_keys() logger.debug('generate role key: %s' % key_path) role = PermRole(name=name, comment=comment, password=encrypt_pass, key_path=key_path) role.save() role.sudo = sudos_obj msg = u"添加系统用户: %s" % name return HttpResponseRedirect(reverse('role_list'))
def regen_ssh_key(request): uuid_r = request.GET.get('uuid', '') user = get_object(User, uuid=uuid_r) if not user: return HttpResponse('没有该用户') username = user.username ssh_key_pass = PyCrypt.gen_rand_pass(16) gen_ssh_key(username, ssh_key_pass) return HttpResponse('ssh密钥已生成,密码为 %s, 请到下载页面下载' % ssh_key_pass)
def perm_role_recycle(request): role_id = request.GET.get('role_id') asset_ids = request.GET.get('asset_id').split(',') # 仅有推送的角色才回收 assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids] recycle_assets = [] for asset in assets: if True in [push.success for push in asset.perm_push.all()]: recycle_assets.append(asset) recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) try: msg_del_user = task.del_user(get_object(PermRole, id=role_id).name) msg_del_sudo = task.del_user_sudo(get_object(PermRole, id=role_id).name) logger.info("recycle user msg: %s" % msg_del_user) logger.info("recycle sudo msg: %s" % msg_del_sudo) except Exception, e: logger.warning("Recycle Role failed: %s" % e) raise ServerError(u"回收已推送的系统用户失败: %s" % e)
def get_asset_group_member(self, str_r): gid_pattern = re.compile(r'^g\d+$') if gid_pattern.match(str_r): gid = int(str_r.lstrip('g')) # 获取资产组包含的资产 asset_group = get_object(AssetGroup, id=gid) if asset_group and asset_group in self.perm_asset_groups: self.search_result = list(asset_group.asset_set.all()) else: color_print('没有该资产组或没有权限') return
def perm_role_delete(request): """ delete role page """ if request.method == "POST": try: # 获取参数删除的role对象 role_id = request.POST.get("id") role = get_object(PermRole, id=role_id) if not role: logger.warning(u"Delete Role: %s not exist" % role.name) raise ServerError(u"%s 无数据记录" % role.name) role_key = role.key_path # 删除推送到主机上的role recycle_assets = [push.asset for push in role.perm_push.all() if push.success] logger.debug(u"delete role %s - delete_assets: %s" % (role.name, recycle_assets)) if recycle_assets: recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) try: msg = task.del_user(get_object(PermRole, id=role_id).name) except Exception, e: logger.warning(u"Recycle Role failed: %s" % e) raise ServerError(u"回收已推送的系统用户失败: %s" % e) logger.info(u"delete role %s - execute delete user: %s" % (role.name, msg)) # TODO: 判断返回结果,处理异常 # 删除存储的秘钥,以及目录 try: key_files = os.listdir(role_key) for key_file in key_files: os.remove(os.path.join(role_key, key_file)) os.rmdir(role_key) except OSError, e: logger.warning(u"Delete Role: delete key error, %s" % e) raise ServerError(u"删除系统用户key失败: %s" % e) logger.info(u"delete role %s - delete role key directory: %s" % (role.name, role_key)) # 数据库里删除记录 role.delete() return HttpResponse(u"删除系统用户: %s" % role.name)
def perm_role_get(request): asset_id = request.GET.get('id', 0) if asset_id: asset = get_object(Asset, id=asset_id) if asset: role = user_have_perm(request.user, asset=asset) logger.debug(u'获取授权系统用户: ' + ','.join([i.name for i in role])) return HttpResponse(','.join([i.name for i in role])) else: roles = get_group_user_perm(request.user).get('role').keys() return HttpResponse(','.join(i.name for i in roles)) return HttpResponse('error')
def perm_role_get(request): asset_id = request.GET.get("id", 0) if asset_id: asset = get_object(Asset, id=asset_id) if asset: role = user_have_perm(request.user, asset=asset) logger.debug("#" + ",".join([i.name for i in role]) + "#") return HttpResponse(",".join([i.name for i in role])) else: roles = get_group_user_perm(request.user).get("role").keys() return HttpResponse(",".join(i.name for i in roles)) return HttpResponse("error")
def perm_role_recycle(request): role_id = request.GET.get('role_id') asset_ids = request.GET.get('asset_id').split(',') # 仅有推送的角色才回收 assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids] recycle_assets = [] for asset in assets: if True in [push.success for push in asset.perm_push.all()]: recycle_assets.append(asset) recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) # TODO: 判断返回结果,处理异常 msg = task.del_user(get_object(PermRole, id=role_id).name) for asset_id in asset_ids: asset = get_object(Asset, id=asset_id) assets.append(asset) role = get_object(PermRole, id=role_id) PermPush.objects.filter(asset=asset, role=role).delete() return HttpResponse('删除成功')
def db_add_group(**kwargs): """ 往数据库添加用户组 :param kwargs: :return: """ name = kwargs.get('name') group = get_object(UserGroup, name=name) users = kwargs.pop('users_id') if not group: group = UserGroup(**kwargs) group.save() for user_id in users: group_add_user(group, user_id)
def send_mail_retry(request): uuid_r = request.GET.get('uuid', '1') user = get_object(User, uuid=uuid_r) msg = u""" 跳板机地址: %s 用户名:%s 重设密码:%s/juser/password/forget/ 请登录web点击个人信息页面重新生成ssh密钥 """ % (URL, user.username, URL) try: send_mail(u'邮件重发', msg, MAIL_FROM, [user.email], fail_silently=False) except IndexError: return Http404 return HttpResponse('发送成功')
def user_del(request): if request.method == "GET": user_ids = request.GET.get('id', '') user_id_list = user_ids.split(',') elif request.method == "POST": user_ids = request.POST.get('id', '') user_id_list = user_ids.split(',') else: return HttpResponse('错误请求') for user_id in user_id_list: user = get_object(User, id=user_id) if user and user.username != 'admin': logger.debug(u"删除用户 %s " % user.username) bash('userdel -r %s' % user.username) user.delete() return HttpResponse('删除成功')
def user_detail(request): header_title, path1, path2 = '用户详情', '用户管理', '用户详情' if request.session.get('role_id') == 0: user_id = request.user.id else: user_id = request.GET.get('id', '') user = get_object(User, id=user_id) if not user: return HttpResponseRedirect(reverse('user_list')) user_perm_info = get_group_user_perm(user) role_assets = user_perm_info.get('role') user_log_ten = Log.objects.filter(user=user.username).order_by('id')[0:10] user_log_last = Log.objects.filter(user=user.username).order_by('id')[0:50] user_log_last_num = len(user_log_last) return my_render('juser/user_detail.html', locals(), request)
def group_edit(request): error = '' msg = '' header_title, path1, path2 = '编辑用户组', '用户管理', '编辑用户组' if request.method == 'GET': group_id = request.GET.get('id', '') user_group = get_object(CMDB_Group, id=group_id) # user_group = UserGroup.objects.get(id=group_id) users_selected = User.objects.filter(group_asset=user_group) users_remain = User.objects.filter(~Q(group_asset=user_group)) users_all = User.objects.all() elif request.method == 'POST': group_id = request.POST.get('group_id', '') group_name = request.POST.get('group_name', '') comment = request.POST.get('comment', '') users_selected = request.POST.getlist('users_selected') try: if '' in [group_id, group_name]: raise ServerError('组名不能为空') if len(CMDB_Group.objects.filter(name=group_name)) > 1: raise ServerError(u'%s 用户组已存在' % group_name) # add user group user_group = get_object_or_404(CMDB_Group, id=group_id) user_group.user_set.clear() for user in User.objects.filter(id__in=users_selected): user.group_asset.add(CMDB_Group.objects.get(id=group_id)) user_group.name = group_name user_group.comment = comment user_group.save() except ServerError, e: error = e if not error: return HttpResponseRedirect(reverse('user_group_list')) else: users_all = User.objects.all() users_selected = User.objects.filter(group=user_group) users_remain = User.objects.filter(~Q(group=user_group))
def down_key(request): if is_role_request(request, 'super'): uuid_r = request.GET.get('uuid', '') else: uuid_r = request.user.uuid if uuid_r: user = get_object(User, uuid=uuid_r) if user: username = user.username private_key_file = os.path.join(KEY_DIR, 'user', username+'.pem') print private_key_file if os.path.isfile(private_key_file): f = open(private_key_file) data = f.read() f.close() response = HttpResponse(data, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(private_key_file) return response return HttpResponse('No Key File. Contact Admin.')
def forget_password(request): if request.method == 'POST': defend_attack(request) email = request.POST.get('email', '') username = request.POST.get('username', '') name = request.POST.get('name', '') user = get_object(User, username=username, email=email, name=name) if user: timestamp = int(time.time()) hash_encode = PyCrypt.md5_crypt(str(user.uuid) + str(timestamp) + KEY) msg = u""" Hi %s, 请点击下面链接重设密码! %s/juser/password/reset/?uuid=%s×tamp=%s&hash=%s """ % (user.name, URL, user.uuid, timestamp, hash_encode) send_mail('忘记跳板机密码', msg, MAIL_FROM, [email], fail_silently=False) msg = u'请登陆邮箱,点击邮件重设密码' return http_success(request, msg) else: error = u'用户不存在或邮件地址错误' return render_to_response('juser/forget_password.html', locals())
def search(self, str_r=""): gid_pattern = re.compile(r"^g\d+$") # 获取用户授权的所有主机信息 if not self.user_perm: self.user_perm = get_group_user_perm(self.user) user_asset_all = self.user_perm.get("asset").keys() # 搜索结果保存 user_asset_search = [] if str_r: # 资产组组id匹配 if gid_pattern.match(str_r): gid = int(str_r.lstrip("g")) # 获取资产组包含的资产 user_asset_search = get_object(AssetGroup, id=gid).asset_set.all() else: # 匹配 ip, hostname, 备注 for asset in user_asset_all: if str_r in asset.ip or str_r in str(asset.hostname) or str_r in str(asset.comment): user_asset_search.append(asset) else: # 如果没有输入就展现所有 user_asset_search = user_asset_all self.search_result = dict(zip(range(len(user_asset_search)), user_asset_search)) color_print("[%-3s] %-12s %-15s %-5s %-10s %s" % ("ID", "主机名", "IP", "端口", "系统用户", "备注"), "title") for index, asset in self.search_result.items(): # 获取该资产信息 asset_info = get_asset_info(asset) # 获取该资产包含的角色 role = [str(role.name) for role in self.user_perm.get("asset").get(asset).get("role")] print "[%-3s] %-15s %-15s %-5s %-10s %s" % ( index, asset.hostname, asset.ip, asset_info.get("port"), role, asset.comment, ) print
print recycle_assets recycle_assets_ip = ','.join( [asset.ip for asset in recycle_assets]) return HttpResponse(recycle_assets_ip) else: return HttpResponse("no such filter_type: %s" % filter_type) else: return HttpResponse("filter_type: ?") except ServerError, e: return HttpResponse(e) if request.method == "POST": try: # 获取参数删除的role对象 role_id = request.POST.get("id") role = get_object(PermRole, id=role_id) if not role: logger.warning(u"Delete Role: role_id %s not exist" % role_id) raise ServerError(u"role_id %s 无数据记录" % role_id) role_key = role.key_path # 删除推送到主机上的role recycle_assets = [ push.asset for push in role.perm_push.all() if push.success ] logger.debug(u"delete role %s - delete_assets: %s" % (role.name, recycle_assets)) if recycle_assets: recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) try: msg = task.del_user(get_object(PermRole, id=role_id).name)
import uuid os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' if not django.get_version().startswith('1.6'): setup = django.setup() from django.contrib.sessions.models import Session from jumpserver.api import ServerError, User, Asset, PermRole, AssetGroup, get_object, mkdir, get_asset_info from jumpserver.api import logger, Log, TtyLog, get_role_key, CRYPTOR, bash, get_tmp_dir from jperm.perm_api import gen_resource, get_group_asset_perm, get_group_user_perm, user_have_perm, PermRole from jumpserver.settings import LOG_DIR, NAV_SORT_BY from jperm.ansible_api import MyRunner # from jlog.log_api import escapeString from jlog.models import ExecLog, FileLog from jlog.views import TermLogRecorder login_user = get_object(User, username=getpass.getuser()) try: remote_ip = os.environ.get('SSH_CLIENT').split()[0] except (IndexError, AttributeError): remote_ip = os.popen("who -m | awk '{ print $NF }'").read().strip('()\n') try: import termios import tty except ImportError: print '\033[1;31m仅支持类Unix系统 Only unix like supported.\033[0m' time.sleep(3) sys.exit() def color_print(msg, color='red', exits=False):
def perm_rule_add(request): """ add rule page 添加授权 """ # 渲染数据 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() if request.method == 'POST': # 获取用户选择的 用户,用户组,资产,资产组,用户角色 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', []) # 需要授权角色 rule_name = request.POST.get('name') rule_comment = request.POST.get('comment') try: rule = get_object(PermRule, name=rule_name) if rule: raise ServerError(u'授权规则 %s 已存在' % rule_name) if not rule_name or not roles_select: raise ServerError(u'系统用户名称和规则名称不能为空') # 获取需要授权的主机列表 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.hostname for asset in need_push_asset]))) # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) rule = PermRule(name=rule_name, comment=rule_comment) rule.save() 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.save() msg = u"添加授权规则:%s" % rule.name return HttpResponseRedirect(reverse('rule_list')) except ServerError, e: error = e
def perm_rule_add(request): """ add rule page 添加授权 """ # 渲染数据 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() if request.method == 'POST': # 获取用户选择的 用户,用户组,资产,资产组,用户角色 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', []) # 需要授权角色 rule_name = request.POST.get('name') rule_comment = request.POST.get('comment') try: rule = get_object(PermRule, name=rule_name) if rule: raise ServerError(u'授权规则 %s 已存在' % rule_name) if not rule_name or not roles_select: raise ServerError(u'系统用户名称和规则名称不能为空') # 获取需要授权的主机列表 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.hostname for asset in need_push_asset]))) # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) rule = PermRule(name=rule_name, comment=rule_comment) rule.save() 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.save() msg = u"添加授权规则:%s" % rule.name return HttpResponseRedirect(reverse('rule_list')) except ServerError, e: error = e
import uuid os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' if not django.get_version().startswith('1.6'): setup = django.setup() from django.contrib.sessions.models import Session from jumpserver.api import ServerError, User, Asset, PermRole, AssetGroup, get_object, mkdir, get_asset_info from jumpserver.api import logger, Log, TtyLog, get_role_key, CRYPTOR, bash, get_tmp_dir from jperm.perm_api import gen_resource, get_group_asset_perm, get_group_user_perm, user_have_perm, PermRole from jumpserver.settings import LOG_DIR, NAV_SORT_BY from jperm.ansible_api import MyRunner # from jlog.log_api import escapeString from jlog.models import ExecLog, FileLog from jlog.views import TermLogRecorder login_user = get_object(User, username=getpass.getuser()) try: remote_ip = os.environ.get('SSH_CLIENT').split()[0] except (IndexError, AttributeError): remote_ip = os.popen("who -m | awk '{ print $NF }'").read().strip('()\n') try: import termios import tty except ImportError: print '\033[1;31m仅支持类Unix系统 Only unix like supported.\033[0m' time.sleep(3) sys.exit() def color_print(msg, color='red', exits=False):
def perm_rule_edit(request): """ edit rule page """ # 渲染数据 header_title, path1, path2 = "授权规则", "规则管理", "添加规则" # 根据rule_id 取得rule对象 rule_id = request.GET.get("id") rule = get_object(PermRule, id=rule_id) # 渲染数据, 获取所选的rule对象 users = User.objects.all() user_groups = UserGroup.objects.all() assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() roles = PermRole.objects.all() if request.method == 'POST' and rule_id: # 获取用户选择的 用户,用户组,资产,资产组,用户角色 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'系统用户和关联系统用户不能为空') 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.hostname 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() msg = u"更新授权规则:%s成功" % rule.name except ServerError, e: error = e
def perm_role_push(request): """ the role push page """ # 渲染数据 header_title, path1, 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.hostname): func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=False, result=failed_asset.get(asset.hostname)) 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())) else: error = u'系统用户 %s 推送失败 [ %s ], 推送成功 [ %s ] 进入系统用户详情,查看失败原因' % (role.name, ','.join(failed_asset.keys()), ','.join(success_asset.keys())) return my_render('jperm/perm_role_push.html', locals(), request)
def perm_role_push(request): """ the role push page """ # 渲染数据 header_title, path1, 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 = {} # 因为要先建立用户,所以password 是必选项,而push key是在 password也完成的情况下的 可选项 # 1. 以秘钥 方式推送角色 if key_push: ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password)) 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 password_push or 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.hostname): func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=False, result=failed_asset.get(asset.hostname)) 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())) else: error = u'系统用户 %s 推送失败 [ %s ], 推送成功 [ %s ] 进入系统用户详情,查看失败原因' % ( role.name, ','.join(failed_asset.keys()), ','.join( success_asset.keys())) return my_render('jperm/perm_role_push.html', locals(), request)
print recycle_assets recycle_assets_ip = ','.join( [asset.ip for asset in recycle_assets]) return HttpResponse(recycle_assets_ip) else: return HttpResponse("no such filter_type: %s" % filter_type) else: return HttpResponse("filter_type: ?") except ServerError, e: return HttpResponse(e) if request.method == "POST": try: # 获取参数删除的role对象 role_id = request.POST.get("id") role = get_object(PermRole, id=role_id) if not role: logger.warning(u"Delete Role: role_id %s not exist" % role_id) raise ServerError(u"role_id %s 无数据记录" % role_id) role_key = role.key_path # 删除推送到主机上的role recycle_assets = [ push.asset for push in role.perm_push.all() if push.success ] logger.debug(u"delete role %s - delete_assets: %s" % (role.name, recycle_assets)) if recycle_assets: recycle_resource = gen_resource(recycle_assets) task = MyTask(recycle_resource) try: msg_del_user = task.del_user(
def perm_rule_edit(request): """ edit rule page """ # 渲染数据 header_title, path1, path2 = "授权规则", "规则管理", "添加规则" # 根据rule_id 取得rule对象 rule_id = request.GET.get("id") rule = get_object(PermRule, id=rule_id) # 渲染数据, 获取所选的rule对象 users = User.objects.all() user_groups = UserGroup.objects.all() assets = Asset.objects.all() asset_groups = AssetGroup.objects.all() roles = PermRole.objects.all() if request.method == 'POST' and rule_id: # 获取用户选择的 用户,用户组,资产,资产组,用户角色 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'系统用户和关联系统用户不能为空') 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.hostname 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() msg = u"更新授权规则:%s成功" % rule.name except ServerError, e: error = e