def login(request, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": if request.POST.has_key('login'): form = authentication_form(request, data=request.POST) if form.is_valid(): if form.get_user() and form.get_user().is_active: # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url( djsettings.LOGIN_REDIRECT_URL) auth_login(request, form.get_user()) Message.objects.create(type=u'用户登录', user=request.user, action=u'用户登录', action_ip=UserIP(request), content='用户登录 %s' % request.user) return HttpResponseRedirect(redirect_to) else: Message.objects.create(type=u'用户登录', user=request.POST.get('username'), action=u'用户登录', action_ip=UserIP(request), content=u'用户登录失败 %s' % request.POST.get('username')) else: form = authentication_form(request) return render(request, 'registration/login.html', { 'form': form, 'title': '用户登录' })
def salt_file_download(request): def file_iterator(file_name, chunk_size=512): with open(file_name) as f: while True: c = f.read(chunk_size) if c: yield c else: break if request.method == 'POST': tgt_select = request.POST.get('tgt_select', None) remote_file = request.POST.get('remote_file', None) sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) ret_bak = sapi.file_bak(tgt_select, 'cp.push', remote_file, 'list') if tgt_select == 'localhost': return render(request, 'redirect.html', {}) remote_path = remote_file.replace(remote_file.split('/')[-1], '') dl_path = './media/salt/filedownload/user_%s/%s%s' % ( request.user.id, tgt_select, remote_path) dl_file = '%s%s' % (dl_path, remote_file.split('/')[-1]) if not os.path.exists(dl_path): os.makedirs(dl_path) try: shutil.copy( '/var/cache/salt/master/minions/%s/files/%s' % (tgt_select, remote_file), dl_file) tar_file = make_tar(dl_file, '/tmp') dl_filename = 'attachment;filename="{0}"'.format( tar_file.replace('/tmp/', '%s%s' % (tgt_select, remote_path))) ret = u'主机:%s\n结果:远程文件 %s 下载成功!' % (tgt_select, remote_file) Message.objects.create(type=u'文件管理', user=request.user, action=u'文件下载', action_ip=UserIP(request), content=u'下载文件 \n%s' % ret) response = StreamingHttpResponse(file_iterator(tar_file)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = dl_filename return response except: print 'No such file or dirctory' ret = u'主机:%s\n结果:远程文件 %s 下载失败,请确认文件是否存在!' % (tgt_select, remote_file) Message.objects.create(type=u'文件管理', user=request.user, action=u'文件下载', action_ip=UserIP(request), content=u'下载文件 \n%s' % ret) return render(request, 'salt_file_download.html', {'ret': ret}) return render(request, 'salt_file_download.html', {})
def logout(request, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Logs out the user and displays 'You are logged out' message. """ Message.objects.create(type=u'用户退出', user=request.user, action=u'用户退出', action_ip=UserIP(request), content='用户退出 %s' % request.user) auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return HttpResponseRedirect('/')
def logoutw(request): Message.objects.create(type=u'用户退出', user=request.user, action=u'用户退出', action_ip=UserIP(request), content='用户退出 %s' % request.user) auth.logout(request) return HttpResponseRedirect('/')
def logout(request): Message.objects.create(type='logout', user=request.user, action=u'logout', action_ip=UserIP(request), content='user_logout {0}'.format(request.user)) auth.logout(request) return HttpResponseRedirect('/')
def salt_key_manage(request, hostname=None): ''' 接受或拒绝salt主机,同时更新数据库 ''' if request.method == 'GET': sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) hostname = request.GET.get('hostname') salthost = SaltHost.objects.get(hostname=hostname) if request.GET.has_key('add'): ret = sapi.accept_key(hostname) if ret: salthost.status = True salthost.save() Message.objects.create(type=u'部署管理', user=request.user, action=u'添加主机', action_ip=UserIP(request), content=u'添加主机 %s' % salthost.hostname) if request.GET.has_key('delete'): ret = sapi.delete_key(hostname) if ret: salthost.status = False salthost.save() Message.objects.create(type=u'部署管理', user=request.user, action=u'删除主机', action_ip=UserIP(request), content=u'删除主机 %s' % salthost.hostname) if request.GET.has_key('flush'): ret = sapi.salt_alive(hostname) if ret: salthost.status = True salthost.save() Message.objects.create(type=u'部署管理', user=request.user, action=u'刷新主机', action_ip=UserIP(request), content=u'刷新主机 %s' % salthost.hostname) return redirect('key_list')
def salt_ajax_module_deploy(request): ''' salt模块部署 ''' rst = RemoteExec(request, fun='state.sls') Message.objects.create(type=u'部署管理', user=request.user, action=rst['jid'], action_ip=UserIP(request), content=u'模块部署 [%s]\n %s' % (rst['arg'], rst['ret'])) return HttpResponse(json.dumps(rst))
def salt_ajax_remote_exec(request): ''' salt远程命令执行 ''' rst = RemoteExec(request, fun='cmd.run') Message.objects.create(type=u'部署管理', user=request.user, action=rst['jid'], action_ip=UserIP(request), content=u'远程管理 [%s]\n %s' % (rst['arg'], rst['ret'])) return HttpResponse(json.dumps(rst))
def salt_ajax_file_upload(request): ''' 执行文件上传 ''' form = SaltFileForm() ret = UploadFile(request, form=form) Message.objects.create(type=u'文件管理', user=request.user, action=u'文件上传', action_ip=UserIP(request), content=u'上传文件 %s' % ret['ret']) return HttpResponse(json.dumps(ret['ret']))
def login(request): if request.method == "POST": if request.POST.has_key('login'): username = request.POST['username'] password = request.POST['password'] #username = up.cleaned_data['username'] #password = up.cleaned_data['password'] user = auth.authenticate(username=username, password=password) if user and user.is_active: auth.login(request, user) Message.objects.create(type='user_login', user=request.user, action='user_Login', action_ip=UserIP(request), content=u'user_login {0}'.format( request.user)) return HttpResponseRedirect('/') else: return render(request, 'registration/login.html', locals()) return render(request, 'registration/login.html', locals())
def login(request): if request.method == "POST": if request.POST.has_key('login'): up = LoginForm(request.POST) if up.is_valid(): username = up.cleaned_data['username'] password = up.cleaned_data['password'] print username, password user = auth.authenticate(username=username, password=password) if user and user.is_active: auth.login(request, user) Message.objects.create(type=u'用户登录', user=request.user, action=u'用户登录', action_ip=UserIP(request), content='用户登录 %s' % request.user) return HttpResponseRedirect('/') else: up = LoginForm() return render(request, 'registration/login.html', { 'up': up, 'title': '用户登录' })
def group_manage(request, aid=None, action=None): if request.user.has_perms(['asset.view_user', 'asset.edit_user']): page_name = '' if aid and action: group = get_object_or_404(UserGroup, pk=aid) if action == 'edit': page_name = '编辑组' if action == 'delete': group.delete() Message.objects.create(type=u'用户分组管理', user=request.user.first_name, action=u'删除分组', action_ip=UserIP(request), content=u'删除分组 %s' % group.name) return redirect('user_group_list') else: group = UserGroup() action = 'add' page_name = '新增用户组' if request.method == 'POST': form = GroupForm(request.POST, instance=group) if form.is_valid(): command_list = form.cleaned_data['command'] directory_list = form.cleaned_data['directory'] user_select = request.POST.getlist('user_sel') user_delete = request.POST.getlist('user_del') host_select = request.POST.getlist('host_sel') host_delete = request.POST.getlist('host_del') group_select = request.POST.getlist('group_sel') group_delete = request.POST.getlist('group_del') perm_select = request.POST.getlist('perm_sel') perm_delete = request.POST.getlist('perm_del') if action == 'add' or action == 'edit': form.save group.save() group.user_group_set.add(*user_select) group.user_group_set.remove(*user_delete) group.user_set.add(*user_select) group.user_set.remove(*user_delete) group.host_usergroup_set.add(*host_select) group.host_usergroup_set.remove(*host_delete) group.group_usergroup_set.add(*group_select) group.group_usergroup_set.remove(*group_delete) group.permissions.add(*perm_select) group.permissions.remove(*perm_delete) if action == 'edit': group.command.clear() group.directory.clear() group.command.add(*command_list) group.directory.add(*directory_list) Message.objects.create(type=u'用户分组管理', user=request.user.first_name, action=page_name, action_ip=UserIP(request), content=u'%s %s' % (page_name, group.name)) return redirect('user_group_list') else: form = GroupForm(instance=group) return render(request, 'userauth_group_manage.html', { 'form': form, 'page_name': page_name, 'action': action, 'aid': aid }) else: raise Http404
def user_manage(request, aid=None, action=None): if request.user.has_perms(['asset.view_user', 'asset.edit_user']): page_name = '' if aid: user = get_object_or_404(User, pk=aid) if action == 'edit': page_name = '编辑用户' if action == 'delete': user.delete() Message.objects.create( type=u'用户管理', user=request.user.first_name, action=u'删除用户', action_ip=UserIP(request), content=u'删除用户 %s%s,用户名 %s' % (user.last_name, user.first_name, user.username)) return redirect('user_list') else: user = User() action = 'add' page_name = '新增用户' if request.method == 'POST': form = UserForm(request.POST, instance=user) if form.is_valid(): password1 = request.POST.get('password1') password2 = request.POST.get('password2') group_select = request.POST.getlist('group_sel') group_delete = request.POST.getlist('group_del') perm_select = request.POST.getlist('perm_sel') perm_delete = request.POST.getlist('perm_del') if action == 'add' or action == 'edit': form.save if password1 and password1 == password2: user.set_password(password1) user.save() # 添加用户至UserGroup user.group.add(*group_select) user.group.remove(*group_delete) # 添加用户至Group组,授权用户该组权限 user.groups.add(*group_select) user.groups.remove(*group_delete) # 授予用户权限 user.user_permissions.add(*perm_select) user.user_permissions.remove(*perm_delete) Message.objects.create(type=u'用户管理', user=request.user.first_name, action=page_name, action_ip=UserIP(request), content=u'%s %s%s,用户名 %s' % (page_name, user.last_name, user.first_name, user.username)) return redirect('user_list') else: form = UserForm(instance=user) return render(request, 'userauth_user_manage.html', { 'form': form, 'page_name': page_name, 'action': action, 'aid': aid }) else: raise Http404
def salt_group_manage(request, id=None): ''' salt主机分组管理,同时更新salt-master配置文件 ''' if request.user.is_superuser: action = '' page_name = '' if id: group = get_object_or_404(SaltGroup, pk=id) action = 'edit' page_name = '编辑分组' else: group = SaltGroup() action = 'add' page_name = '新增分组' if request.method == 'GET': if request.GET.has_key('delete'): id = request.GET.get('id') group = get_object_or_404(SaltGroup, pk=id) group.delete() Message.objects.create(type=u'部署管理', user=request.user, action=u'删除分组', action_ip=UserIP(request), content='删除分组 %s' % group.nickname) with open('./saltconfig/nodegroup.conf', 'r') as f: with open('./nodegroup', 'w') as g: for line in f.readlines(): if group.groupname not in line: g.write(line) shutil.move('./nodegroup', './saltconfig/nodegroup.conf') return redirect('group_list') if request.method == 'POST': form = SaltGroupForm(request.POST, instance=group) if form.is_valid(): minions = request.POST.getlist('minions') # 前台分组以别名显示,组名不变 if action == 'add': group = form.save(commit=False) group.groupname = form.cleaned_data['nickname'] else: try: group.minions.clear() except: pass form.save group.save() for m in minions: group.minions.add(m) Message.objects.create(type=u'部署管理', user=request.user, action=page_name, action_ip=UserIP(request), content='%s %s' % (page_name, group.nickname)) minions_l = [] for m in group.minions.values('hostname'): minions_l.append(m['hostname']) minions_str = ','.join(minions_l) try: with open('./saltconfig/nodegroup.conf', 'r') as f: with open('./nodegroup', 'w') as g: for line in f.readlines(): if group.groupname not in line: g.write(line) g.write(" %s: 'L@%s'\n" % (group.groupname, minions_str)) shutil.move('./nodegroup', './saltconfig/nodegroup.conf') except: with open('./saltconfig/nodegroup.conf', 'w') as g: g.write("nodegroups:\n %s: 'L@%s'\n" % (group.groupname, minions_str)) import subprocess subprocess.Popen('systemctl restart salt-api', shell=True) return redirect('group_list') else: form = SaltGroupForm(instance=group) return render(request, 'salt_group_manage.html', { 'form': form, 'action': action, 'page_name': page_name }) else: raise Http404
def salt_module_manage(request, id=None): ''' 模块管理 ''' ret = '' upload_stat = True if id: module = get_object_or_404(ModuleUpload, pk=id) old_path = module.upload_path.path.split('.') action = 'edit' page_name = '编辑模块' else: module = ModuleUpload() action = 'add' page_name = '新增模块' if request.method == 'GET': if request.GET.has_key('delete'): id = request.GET.get('id') module = get_object_or_404(ModuleUpload, pk=id) module.delete() Message.objects.create(type=u'部署管理', user=request.user, action=u'删除模块', action_ip=UserIP(request), content=u'删除模块 %s' % module.name) cur_path = module.upload_path.path.split('.')[0] try: os.remove('%s.sls' % (cur_path)) except: shutil.rmtree(cur_path, ignore_errors=True) return redirect('module_list') if request.method == 'POST': ext_path = './media/salt/module/user_%s' % request.user.id form = ModuleForm(request.POST, request.FILES, instance=module) if form.is_valid(): file_exists = request.POST.get('upload_path') file_name = form.cleaned_data['upload_path'] file_ext = str(file_name).split('.')[-1] ext = ['bz2', 'gz', 'zip', 'sls'] if file_ext in ext: if action == 'add': module = form.save(commit=False) else: form.save module.user = request.user module.save() Message.objects.create(type=u'部署管理', user=request.user, action=page_name, action_ip=UserIP(request), content='%s %s' % (page_name, module.name)) src = module.upload_path.path if file_exists == None: try: os.remove('%s.sls' % old_path[0]) except: pass try: if file_ext == 'zip': tar = zipfile.ZipFile(src) else: tar = tarfile.open(src) tar.extractall(path=ext_path) tar.close() ret = u'模块 %s 已上传完成!' % (file_name) except: upload_stat = False ret = u'模块 %s 上传失败,请上传.sls文件或.tar.gz/.tar.bz2/.zip压缩包并确认压缩文件是否损坏!' % ( file_name) try: os.remove(src) except: shutil.rmtree(src, ignore_errors=True) pass if upload_stat: return redirect('module_list') else: return render( request, 'salt_module_manage.html', { 'form': form, 'action': action, 'page_name': page_name, 'ret': ret }) else: ret = u'不支持的文件格式,请上传.sls文件或.tar.gz/.tar.bz2/.zip压缩包!' else: form = ModuleForm(instance=module) return render(request, 'salt_module_manage.html', { 'form': form, 'action': action, 'page_name': page_name, 'ret': ret })
def salt_advanced_manage(request): ret = '' if request.method == 'POST': if request.is_ajax(): tgt_selects = request.POST.getlist('tgt_select', None) args = request.POST.getlist('arg', None) checkgrp = request.POST.getlist('ifcheck', None) check_type = request.POST.get('check_type', None) if check_type == 'panel-group': expr_form = 'nodegroup' else: expr_form = 'list' s = '::'.join(str(i) for i in checkgrp) checkgrp = s.replace('0::1', '1').split('::') sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) for i in range(0, len(tgt_selects)): try: jid = sapi.remote_execution(tgt_selects[i], 'cmd.run', args[i] + ';echo ":::"$?', expr_form) if check_type == 'panel-group': s = SaltGroup.objects.get(groupname=tgt_selects[i]) s_len = s.minions.all().count() else: s = tgt_selects[i].split(',') s_len = len(s) rst = {} while (len(rst) < s_len): rst = sapi.salt_runner(jid) #time.sleep(1) j = 0 for k in rst: ret = ret + u'L%s-%s 主机:' % ( i, j) + k + '\n运行结果:\n' + rst[k] + '\n' j = j + 1 r = rst[k].split(':::')[-1].strip() if r != '0': ret = ret + '%s 执行失败!\nJobs NO. %s\n' % ( args[i], jid) + '-' * 80 + '\n' if checkgrp[i] == '0': try: Message.objects.create( type=u'部署管理', user=request.user, action=jid, action_ip=UserIP(request), content=u'高级管理 %s' % ret) except: print 'Log Err' return HttpResponse(json.dumps(ret)) else: continue else: ret = ret + '%s 执行成功!\nJobs NO. %s\n' % ( args[i], jid) + '-' * 80 + '\n' except: print 'Err' try: Message.objects.create(type=u'部署管理', user=request.user, action=jid, action_ip=UserIP(request), content=u'高级管理 %s' % ret) except: print 'Log Err' return HttpResponse(json.dumps(ret)) return render(request, 'salt_remote_exec_advance.html', {'ret': ret})
def salt_ajax_file_rollback(request): ''' 执行文件回滚 ''' true = True if request.method == 'POST': if request.is_ajax(): r_list = [] if request.POST.get('check_type') == 'rollback_file': if request.POST.get('get_type') == 'panel-group': grp = request.POST.get('tgt_select') tgt_select = SaltGroup.objects.get(nickname=grp).groupname else: tgt_select = request.POST.get('tgt_select') rollback_list = FileRollback.objects.filter(target=tgt_select) r_list = [] for r in rollback_list: r_list.append(r.cur_path) func = lambda x, y: x if y in x else x + [y] r_list = reduce(func, [ [], ] + r_list) return HttpResponse(json.dumps(r_list)) if request.POST.get('check_type') == 'rollback_history_list': if request.POST.get('get_type') == 'panel-group': grp = request.POST.get('tgt_select') tgt_select = SaltGroup.objects.get(nickname=grp).groupname else: tgt_select = request.POST.get('tgt_select') cur_path = request.POST.get('rollback_list', None) rollback_history_list = FileRollback.objects.filter( cur_path=cur_path).filter(target=tgt_select) for r in rollback_history_list: r_list.append(r.bak_path) return HttpResponse(json.dumps(r_list)) if request.POST.get('check_type') == 'rollback_history_remark': if request.POST.get('get_type') == 'panel-group': grp = request.POST.get('tgt_select') tgt_select = SaltGroup.objects.get(nickname=grp).groupname else: tgt_select = request.POST.get('tgt_select') bak_path = request.POST.get('rollback_remark', None) rollback_history_remark = FileRollback.objects.filter( bak_path=bak_path).filter(target=tgt_select) for r in rollback_history_remark: r_list.append(r.remark) return HttpResponse(json.dumps(r_list)) else: if request.POST.get('check_type') == 'panel-group': grp = request.POST.get('tgt_select') tgt_select = SaltGroup.objects.get(nickname=grp).groupname expr_form = 'nodegroup' else: tgt_select = request.POST.get('tgt_select') expr_form = 'list' remote_path = request.POST.get('remote_path') history_version = request.POST.get('history_version') sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) ret = sapi.file_copy(tgt_select, 'cp.get_file', history_version, remote_path, expr_form) rst = '' for k in ret: rst = rst + u'主机:' + k + '\n回滚结果:\n' + ret[ k] + '\n' + '-' * 80 + '\n' Message.objects.create(type=u'文件管理', user=request.user, action=u'文件回滚', action_ip=UserIP(request), content=u'文件回滚 %s' % rst) return HttpResponse(json.dumps(rst))