Esempio n. 1
0
def user_delete(request):
    pk = request.POST.get('id', None)
    try:
        ids = [int(x) for x in pk.split(',')]
    except Exception:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 401, "err": error_message})
    if not ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 402, "err": error_message})
    remoteusers = RemoteUser.objects.filter(pk__in=ids)
    if not remoteusers:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 403, "err": error_message})
    remoteusernames = list()
    for remoteuser in remoteusers:
        if remoteuser.remoteuserbindhost_set.all().count() != 0:
            continue
        remoteuser.delete()
        remoteusernames.append(remoteuser.name)
    loguser = User.objects.get(username=request.session.get('username'))
    event_log(loguser, 16, '主机用户 [{}] 删除成功'.format(','.join(remoteusernames)),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 2
0
def session_close(request):
    pk = request.POST.get('id', None)
    group = request.POST.get('group', None)
    if not pk or not group:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    terminalsession = get_object_or_404(TerminalSession, pk=pk)
    try:
        channel_layer = get_channel_layer()
        # async_to_sync(channel_layer.send)(terminalsession.name, {
        #     "type": "chat.message",
        #     "text": '{"status":2, "message":"\\n\\rAdministrator forcibly interrupts your connection"}',
        # })
        async_to_sync(channel_layer.group_send)(group, {
            "type": "chat.message",
            "text": '{"status":2, "message":"\\n\\r当前会话已被管理员关闭"}',
        })
        try:
            terminalsession.delete()
        except Exception:
            pass
        event_log(request.session.get('username'), 18, '会话 [{}] 强制停止成功'.format(terminalsession.name),
                        request.META.get('REMOTE_ADDR', None), request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 200, "err": ""})
    except Exception:
        error_message = '未知错误!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 3
0
def session_clissh_close(request):
    pk = request.POST.get('id', None)
    name = request.POST.get('session', None)
    if not pk or not name:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    name = name.strip()
    terminalsession = get_object_or_404(TerminalSession, pk=pk)
    if terminalsession.name != name:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    try:
        cache.delete(name)
        try:
            terminalsession.delete()
        except Exception:
            pass
        event_log(request.session.get('username'), 18,
                  '会话 [{}] 强制停止成功'.format(terminalsession.name),
                  request.META.get('REMOTE_ADDR', None),
                  request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 200, "err": ""})
    except Exception:
        error_message = '未知错误!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 4
0
def session_unlock(request):
    pk = request.POST.get('id', None)
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    terminalsession = get_object_or_404(TerminalSession, pk=pk)
    try:
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.send)(
            terminalsession.name, {
                "type": "unlock.message",
                "text": request.session.get('username'),
            })
        try:
            TerminalSession.objects.filter(pk=pk).update(locked=False)
        except Exception:
            pass
        event_log(request.session.get('username'), 20,
                  '会话 [{}] 解锁成功'.format(terminalsession.name),
                  request.META.get('REMOTE_ADDR', None),
                  request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 200, "err": ""})
    except Exception:
        error_message = '未知错误!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 5
0
def session_rdp_close(request):
    pk = request.POST.get('id', None)
    group = request.POST.get('group', None)
    if not pk or not group:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    terminalsession = get_object_or_404(TerminalSession, pk=pk)
    try:
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            group, {
                "type": "close.message",
                "text": request.session.get('username'),
            })
        try:
            terminalsession.delete()
        except Exception:
            pass
        event_log(request.session.get('username'), 18,
                  '会话 [{}] 强制停止成功'.format(terminalsession.name),
                  request.META.get('REMOTE_ADDR', None),
                  request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 200, "err": ""})
    except Exception:
        error_message = '未知错误!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 6
0
def group_delete(request):
    pk = request.POST.get('id', None)
    try:
        ids = [int(x) for x in pk.split(',')]
    except Exception:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 401, "err": error_message})
    if not ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 402, "err": error_message})
    groups = Group.objects.filter(pk__in=ids)
    if not groups:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 403, "err": error_message})
    groupnames = list()
    for group in groups:
        if group.user_set.all().count(
        ) != 0 or group.remote_user_bind_hosts.all().count() != 0:
            continue
        group.delete()
        groupnames.append(group.group_name)
    if not groupnames:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 404, "err": error_message})
    user = User.objects.get(username=request.session.get('username'))
    event_log(user, 9, '组 [{}] 删除成功'.format(','.join(groupnames)),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 7
0
def host_delete(request):
    pk = request.POST.get('id', None)
    try:
        ids = [int(x) for x in pk.split(',')]
    except Exception:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 401, "err": error_message})
    if not ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 402, "err": error_message})
    if request.session['issuperuser'] and request.session[
            'username'] == 'admin':
        hosts = RemoteUserBindHost.objects.filter(pk__in=ids)
    else:
        hosts = RemoteUserBindHost.objects.filter(
            Q(user__username=request.session['username'])
            | Q(group__user__username=request.session['username']),
            pk__in=ids)
    if not hosts:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 403, "err": error_message})
    hostnames = list()
    for host in hosts:
        host.delete()
        hostnames.append(host.hostname)
    loguser = User.objects.get(username=request.session.get('username'))
    event_log(loguser, 13, '主机 [{}] 删除成功'.format(','.join(hostnames)),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 8
0
def group_update(request):
    changegroup_form = ChangeGroupForm(request.POST)
    if changegroup_form.is_valid():
        log_user = request.session.get('username')
        groupid = changegroup_form.cleaned_data.get('groupid')
        memo = changegroup_form.cleaned_data.get('memo')
        users = changegroup_form.cleaned_data.get('users')
        if users:
            try:
                users = [int(user) for user in users.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            users = None

        hosts = changegroup_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        data = {
            'memo': memo,
        }

        try:
            user = User.objects.get(username=log_user)
            Group.objects.filter(id=groupid).update(**data)
            update_group = Group.objects.get(id=groupid)
            if users:  # 更新用户组
                update_users = User.objects.filter(id__in=users)
                update_group.user_set.set(update_users)
            else:
                update_group.user_set.clear()

            if hosts:  # 更新主机多对多字段
                update_hosts = RemoteUserBindHost.objects.filter(id__in=hosts)
                update_group.remote_user_bind_hosts.set(update_hosts)
            else:
                update_group.remote_user_bind_hosts.clear()

            update_group.save()
            event_log(user, 11,
                      '组 [{}] 更新信息成功'.format(update_group.group_name),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '组不存在!'
            return JsonResponse({"code": 402, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 403, "err": error_message})
Esempio n. 9
0
def group_add(request):
    addgroup_form = AddGroupForm(request.POST)
    if addgroup_form.is_valid():
        log_user = request.session.get('username')
        groupname = addgroup_form.cleaned_data.get('groupname')
        memo = addgroup_form.cleaned_data.get('memo')
        hosts = addgroup_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        data = {
            'group_name': groupname,
            'memo': memo,
        }

        try:
            user = User.objects.get(username=log_user)
            if HostGroup.objects.filter(group_name=groupname,
                                        user=user).count() > 0:
                error_message = '主机组已存在'
                return JsonResponse({"code": 402, "err": error_message})
            data['user'] = user
            update_group = HostGroup.objects.create(**data)

            if hosts:  # 更新主机多对多字段
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_hosts = RemoteUserBindHost.objects.filter(
                        id__in=hosts, enabled=True)
                else:
                    update_hosts = RemoteUserBindHost.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        Q(id__in=hosts),
                        enabled=True)
                update_group.remoteuserbindhost_set.set(update_hosts)
            else:
                update_group.remoteuserbindhost_set.clear()

            update_group.save()
            event_log(user, 21,
                      '主机组 [{}] 添加成功'.format(update_group.group_name),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '主机组添加错误!'
            return JsonResponse({"code": 403, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 404, "err": error_message})
Esempio n. 10
0
def login(request):
    if request.session.get('islogin', None):  # 不允许重复登录
        return redirect(reverse('server:index'))
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        error_message = '请检查填写的内容!'
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')
            try:
                user = User.objects.get(username=username)
                if not user.enabled:
                    error_message = '用户已禁用!'
                    event_log(user, 3, '用户 [{}] 已禁用'.format(username),
                              request.META.get('REMOTE_ADDR', None),
                              request.META.get('HTTP_USER_AGENT', None))
                    return render(request, 'user/login.html', locals())
            except Exception:
                error_message = '用户不存在!'
                event_log(None, 3, '用户 [{}] 不存在'.format(username),
                          request.META.get('REMOTE_ADDR', None),
                          request.META.get('HTTP_USER_AGENT', None))
                return render(request, 'user/login.html', locals())
            # if user.password == password:
            if user.password == hash_code(password):
                data = {'last_login_time': timezone.now()}
                User.objects.filter(username=username).update(**data)
                request.session.set_expiry(0)
                request.session['issuperuser'] = False
                if user.role == 1:  # 超级管理员
                    request.session['issuperuser'] = True
                request.session['islogin'] = True
                request.session['userid'] = user.id
                request.session['username'] = user.username
                request.session['nickname'] = user.nickname
                request.session['locked'] = False  # 锁定屏幕
                now = int(time.time())
                request.session['logintime'] = now
                request.session['lasttime'] = now
                event_log(user, 1, '用户 [{}] 登陆成功'.format(username),
                          request.META.get('REMOTE_ADDR', None),
                          request.META.get('HTTP_USER_AGENT', None))
                return redirect(reverse('server:index'))
            else:
                error_message = '密码错误!'
                event_log(user, 3, '用户 [{}] 密码错误'.format(username),
                          request.META.get('REMOTE_ADDR', None),
                          request.META.get('HTTP_USER_AGENT', None))
                return render(request, 'user/login.html', locals())
        else:
            event_log(None, 3, '登陆表单验证错误',
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return render(request, 'user/login.html', locals())
    return render(request, 'user/login.html')
Esempio n. 11
0
def host_update(request):
    changehost_form = ChangeHostForm(request.POST)
    if changehost_form.is_valid():
        log_user = request.session.get('username')
        hostid = changehost_form.cleaned_data.get('hostid')
        type = changehost_form.cleaned_data.get('type')
        ip = changehost_form.cleaned_data.get('ip')
        wip = changehost_form.cleaned_data.get('wip')
        protocol = changehost_form.cleaned_data.get('protocol')
        security = changehost_form.cleaned_data.get('security', None)
        env = changehost_form.cleaned_data.get('env')
        platform = changehost_form.cleaned_data.get('platform')
        port = changehost_form.cleaned_data.get('port')
        release = changehost_form.cleaned_data.get('release')
        memo = changehost_form.cleaned_data.get('memo')
        enabled = changehost_form.cleaned_data.get('enabled')
        binduserid = changehost_form.cleaned_data.get('binduserid')
        data = {
            'type': type,
            'ip': ip,
            'wip': wip,
            'protocol': protocol,
            'security': security,
            'env': env,
            'platform': platform,
            'port': port,
            'release': release,
            'memo': memo,
            'enabled': enabled,
        }
        try:
            user = User.objects.get(username=log_user)
            remoteuser = RemoteUser.objects.get(id=binduserid)
            data['remote_user'] = remoteuser
            if request.session['issuperuser'] and request.session[
                    'username'] == 'admin':
                RemoteUserBindHost.objects.filter(id=hostid).update(**data)
            else:
                RemoteUserBindHost.objects.filter(
                    Q(user__username=request.session['username'])
                    | Q(group__user__username=request.session['username']),
                    id=hostid).update(**data)
            event_log(
                user, 14, '主机 [{}] 更新成功'.format(
                    RemoteUserBindHost.objects.get(id=hostid).hostname),
                request.META.get('REMOTE_ADDR', None),
                request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '未知错误!'
            return JsonResponse({"code": 400, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 12
0
def group_delete(request):
    pk = request.POST.get('id', None)
    user = User.objects.get(id=int(request.session.get('userid')))
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    group = get_object_or_404(HostGroup, pk=pk, user=user)
    group.delete()
    event_log(user, 22, '主机组 [{}] 删除成功'.format(group.group_name),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 13
0
def host_delete(request):
    pk = request.POST.get('id', None)
    loguser = User.objects.get(username=request.session.get('username'))
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    host = get_object_or_404(RemoteUserBindHost, pk=pk)
    host.delete()
    event_log(loguser, 13, '主机 [{}] 删除成功'.format(host.hostname),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 14
0
def user_add(request):
    adduser_form = AddUserForm(request.POST)
    if adduser_form.is_valid():
        log_user = request.session.get('username')
        name = adduser_form.cleaned_data.get('name')
        username = adduser_form.cleaned_data.get('username')
        password = adduser_form.cleaned_data.get('password')
        domain = adduser_form.cleaned_data.get('domain', None)
        memo = adduser_form.cleaned_data.get('memo')
        enabled = adduser_form.cleaned_data.get('enabled')
        superusername = adduser_form.cleaned_data.get('superusername', None)
        superpassword = adduser_form.cleaned_data.get('superpassword', None)
        if enabled:
            if not superusername or not superpassword:
                error_message = '超级用户或者超级密码不能为空!'
                return JsonResponse({"code": 400, "err": error_message})

        data = {
            'name':
            name,
            'username':
            username,
            'password':
            encrypt(password),
            'domain':
            domain,
            'memo':
            memo,
            'enabled':
            enabled,
            'superusername':
            superusername,
            'superpassword':
            encrypt(superpassword) if superpassword else superpassword,
        }
        try:
            if RemoteUser.objects.filter(name=name).count() > 0:
                error_message = '主机用户已存在'
                return JsonResponse({"code": 401, "err": error_message})
            user = User.objects.get(username=log_user)
            update_user = RemoteUser.objects.create(**data)
            event_log(user, 15, '主机用户 [{}] 添加成功'.format(update_user.name),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '未知错误!'
            return JsonResponse({"code": 402, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 403, "err": error_message})
Esempio n. 15
0
def user_update(request):
    changeuser_form = ChangeUserForm(request.POST)
    if changeuser_form.is_valid():
        log_user = request.session.get('username')
        userid = changeuser_form.cleaned_data.get('userid')
        username = changeuser_form.cleaned_data.get('username')
        password = changeuser_form.cleaned_data.get('password')
        domain = changeuser_form.cleaned_data.get('domain', None)
        memo = changeuser_form.cleaned_data.get('memo')
        enabled = changeuser_form.cleaned_data.get('enabled')
        superusername = changeuser_form.cleaned_data.get('superusername', None)
        superpassword = changeuser_form.cleaned_data.get('superpassword', None)
        if enabled:
            if not superusername or not superpassword:
                error_message = '超级用户或者超级密码不能为空!'
                return JsonResponse({"code": 400, "err": error_message})

        data = {
            'username':
            username,
            'password':
            encrypt(password),
            'domain':
            domain,
            'memo':
            memo,
            'enabled':
            enabled,
            'superusername':
            superusername,
            'superpassword':
            encrypt(superpassword) if superpassword else superpassword,
        }
        try:
            user = User.objects.get(username=log_user)
            RemoteUser.objects.filter(id=userid).update(**data)
            event_log(
                user, 17, '主机用户 [{}] 更新成功'.format(
                    RemoteUser.objects.get(id=userid).name),
                request.META.get('REMOTE_ADDR', None),
                request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '主机用户不存在!'
            return JsonResponse({"code": 401, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 402, "err": error_message})
Esempio n. 16
0
def user_delete(request):
    pk = request.POST.get('id', None)
    loguser = User.objects.get(username=request.session.get('username'))
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    remoteuser = get_object_or_404(RemoteUser, pk=pk)
    if remoteuser.remoteuserbindhost_set.all().count() != 0:
        error_message = '用户已绑定主机!'
        return JsonResponse({"code": 401, "err": error_message})
    remoteuser.delete()
    event_log(loguser, 16, '主机用户 [{}] 删除成功'.format(remoteuser.name),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 17
0
def group_delete(request):
    pk = request.POST.get('id', None)
    user = User.objects.get(username=request.session.get('username'))
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    group = get_object_or_404(Group, pk=pk)
    if group.user_set.all().count() != 0 or group.remote_user_bind_hosts.all(
    ).count() != 0:
        error_message = '组内存在用户或者主机!'
        return JsonResponse({"code": 401, "err": error_message})
    group.delete()
    event_log(user, 9, '组 [{}] 删除成功'.format(group.group_name),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 18
0
def session_clissh_unlock(request):
    pk = request.POST.get('id', None)
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    terminalsession = get_object_or_404(TerminalSession, pk=pk)
    try:
        # 解锁会话
        cache.delete(terminalsession.name + '_lock')
        try:
            TerminalSession.objects.filter(pk=pk).update(locked=False)
        except Exception:
            pass
        event_log(request.session.get('username'), 20, '会话 [{}] 解锁成功'.format(terminalsession.name),
                        request.META.get('REMOTE_ADDR', None), request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 200, "err": ""})
    except Exception:
        error_message = '未知错误!'
        return JsonResponse({"code": 401, "err": error_message})
Esempio n. 19
0
def user_delete(request):
    pk = request.POST.get('id', None)
    loguser = User.objects.get(username=request.session.get('username'))
    if not pk:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    if pk == request.session.get('userid'):
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 400, "err": error_message})
    user = get_object_or_404(User, pk=pk)
    if user.groups.all().count() != 0 or user.remote_user_bind_hosts.all(
    ).count() != 0:
        error_message = '用户下存在主机或者属于其他组!'
        return JsonResponse({"code": 401, "err": error_message})
    user.delete()
    event_log(loguser, 7, '用户 [{}] 删除成功'.format(user.username),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 20
0
def client_upload(request):
    response = {'status': '-1'}
    try:
        data = json.loads(json.loads(request.body.decode()))
        protocol_choice = {
            'http': 1,
            'https': 2
        }
        scheduler_host = SchedulerHost.objects.filter(ip=request.META['REMOTE_ADDR'], port=data['port'], token=data['token'])
        if not scheduler_host:
            SchedulerHost.objects.create(
                hostname=data['hostname'],
                ip=request.META['REMOTE_ADDR'],
                protocol=protocol_choice[data['protocol']],
                port=data['port'],
                token=data['token'],
                status=True,
                cron=data['cron'],
                interval=data['interval'],
                date=data['date'],
                executed=data['executed'],
                failed=data['failed']
            )
            event_log(None, 24, '自动添加调度主机 [{}_{}_{}_{}] 成功'.format(data['hostname'],
                      request.META['REMOTE_ADDR'], data['protocol'], data['port']),
                      request.META.get('REMOTE_ADDR', None), request.META.get('HTTP_USER_AGENT', None))
        else:
            scheduler_host[0].status = True
            scheduler_host[0].cron = data['cron']
            scheduler_host[0].interval = data['interval']
            scheduler_host[0].date = data['date']
            scheduler_host[0].executed = data['executed']
            scheduler_host[0].failed = data['failed']
            scheduler_host[0].save()
    except Exception as e:
        print(traceback.format_exc())
        response['msg'] = str(e)
    else:
        response['status'] = 0
        response['msg'] = ''
    return JsonResponse(response)
Esempio n. 21
0
def logout(request):
    if not request.session.get('islogin', None):
        return redirect(reverse('user:login'))
    user = User.objects.get(id=int(request.session.get('userid')))
    # request.session.flush()     # 清除所有后包括django-admin登陆状态也会被清除
    # 或者使用下面的方法
    try:
        del request.session['issuperuser']
        del request.session['islogin']
        del request.session['userid']
        del request.session['username']
        del request.session['nickname']
        del request.session['locked']
        del request.session['logintime']
        del request.session['lasttime']
        del request.session['referer_url']
    except Exception:
        pass
    event_log(user, 2, '用户 [{}] 退出'.format(user.username),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return redirect(reverse('user:login'))
Esempio n. 22
0
def group_delete(request):
    pk = request.POST.get('id', None)
    try:
        ids = [int(x) for x in pk.split(',')]
    except Exception:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 401, "err": error_message})
    if not ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 402, "err": error_message})
    user = User.objects.get(id=int(request.session.get('userid')))
    groups = HostGroup.objects.filter(pk__in=ids, user=user)
    if not groups:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 403, "err": error_message})
    groupnames = list()
    for group in groups:
        group.delete()
        groupnames.append(group.group_name)
    event_log(user, 22, '主机组 [{}] 删除成功'.format(','.join(groupnames)),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 23
0
def user_delete(request):
    """
    支持批量删除
    """
    pk = request.POST.get('id', None)
    try:
        ids = [int(x) for x in pk.split(',')]
    except Exception:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 401, "err": error_message})
    if not ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 402, "err": error_message})
    if request.session.get('userid') in ids:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 403, "err": error_message})
    users = User.objects.filter(pk__in=ids)
    if not users:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 404, "err": error_message})
    usernames = list()
    for user in users:
        if user.username == 'admin' and user.role == 1:
            continue
        if user.groups.all().count() != 0 or user.remote_user_bind_hosts.all(
        ).count() != 0:
            continue
        user.delete()
        usernames.append(user.username)
    if not usernames:
        error_message = '不合法的请求参数!'
        return JsonResponse({"code": 405, "err": error_message})
    loguser = User.objects.get(username=request.session.get('username'))
    event_log(loguser, 7, '用户 [{}] 删除成功'.format(','.join(usernames)),
              request.META.get('REMOTE_ADDR', None),
              request.META.get('HTTP_USER_AGENT', None))
    return JsonResponse({"code": 200, "err": ""})
Esempio n. 24
0
def user_update(request):
    changeuser_form = ChangeUserForm(request.POST)
    if changeuser_form.is_valid():
        log_user = request.session.get('username')
        userid = changeuser_form.cleaned_data.get('userid')
        nickname = changeuser_form.cleaned_data.get('nickname')
        email = changeuser_form.cleaned_data.get('email')
        phone = changeuser_form.cleaned_data.get('phone')
        weixin = changeuser_form.cleaned_data.get('weixin')
        qq = changeuser_form.cleaned_data.get('qq')
        sex = changeuser_form.cleaned_data.get('sex')
        memo = changeuser_form.cleaned_data.get('memo')
        enabled = changeuser_form.cleaned_data.get('enabled')
        role = changeuser_form.cleaned_data.get('role')
        groups = changeuser_form.cleaned_data.get('groups')
        if groups:
            try:
                groups = [int(group) for group in groups.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            groups = None

        hosts = changeuser_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        permissions = changeuser_form.cleaned_data.get('permissions')
        if permissions:
            try:
                permissions = [
                    int(permissions) for permissions in permissions.split(',')
                ]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            permissions = None

        data = {
            'nickname': nickname,
            'email': email,
            'phone': phone,
            'weixin': weixin,
            'qq': qq,
            'sex': sex,
            'memo': memo,
            'enabled': enabled,
            'role': role,
        }
        try:
            user = User.objects.get(username=log_user)
            User.objects.filter(id=userid).update(**data)
            update_user = User.objects.get(id=userid)
            if update_user.id == request.session['userid'] or (
                    update_user.username == 'admin' and update_user.role == 1):
                raise Http404('Not found')
            if groups:  # 更新组多对多字段
                update_groups = Group.objects.filter(id__in=groups)
                update_user.groups.set(update_groups)
            else:
                update_user.groups.clear()

            other_hosts = None
            if not request.session[
                    'issuperuser'] or request.session['username'] != 'admin':
                # 修改的用户中可能存在拥有的主机但是操作用户没有此主机的情况
                other_hosts = RemoteUserBindHost.objects.filter(
                    Q(user__id=userid)).filter(
                        ~Q(user__username=request.session['username'])
                        & ~Q(group__user__username=request.session['username'])
                    ).distinct()

            other_permissions = None
            if not request.session[
                    'issuperuser'] or request.session['username'] != 'admin':
                # 修改的用户中可能存在拥有的权限但是操作用户没有此权限的情况
                other_permissions = Permission.objects.filter(
                    Q(user__id=userid)).filter(
                        ~Q(user__username=request.session['username'])
                        & ~Q(group__user__username=request.session['username'])
                    ).distinct()

            if hosts:  # 更新主机多对多字段
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_hosts = RemoteUserBindHost.objects.filter(
                        id__in=hosts)
                else:
                    update_hosts = RemoteUserBindHost.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=hosts).distinct()
                update_user.remote_user_bind_hosts.set(update_hosts)
            else:
                update_user.remote_user_bind_hosts.clear()

            if permissions:
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_permissions = Permission.objects.filter(
                        id__in=permissions)
                else:
                    update_permissions = Permission.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=permissions).distinct()
                update_user.permission.set(update_permissions)
            else:
                update_user.permission.clear()

            if other_hosts:
                for i in other_hosts:
                    update_user.remote_user_bind_hosts.add(i)

            if other_permissions:
                for i in other_permissions:
                    update_user.permission.add(i)

            update_user.save()
            event_log(user, 10, '用户 [{}] 更新信息成功'.format(update_user.username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '用户不存在!'
            return JsonResponse({"code": 402, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 403, "err": error_message})
Esempio n. 25
0
def profile_update(request):
    changeuserprofile_form = ChangeUserProfileForm(request.POST)
    if changeuserprofile_form.is_valid():
        userid = request.session.get('userid')
        username = request.session.get('username')
        nickname = changeuserprofile_form.cleaned_data.get('nickname')
        email = changeuserprofile_form.cleaned_data.get('email')
        phone = changeuserprofile_form.cleaned_data.get('phone')
        weixin = changeuserprofile_form.cleaned_data.get('weixin')
        qq = changeuserprofile_form.cleaned_data.get('qq')
        sex = changeuserprofile_form.cleaned_data.get('sex')
        memo = changeuserprofile_form.cleaned_data.get('memo')
        clissh_name = changeuserprofile_form.cleaned_data.get('clissh_name')
        clissh_path = changeuserprofile_form.cleaned_data.get('clissh_path')
        clissh_args = changeuserprofile_form.cleaned_data.get('clissh_args')
        clisftp_name = changeuserprofile_form.cleaned_data.get('clisftp_name')
        clisftp_path = changeuserprofile_form.cleaned_data.get('clisftp_path')
        clisftp_args = changeuserprofile_form.cleaned_data.get('clisftp_args')
        data = {
            'nickname': nickname,
            'email': email,
            'phone': phone,
            'weixin': weixin,
            'qq': qq,
            'sex': sex,
            'memo': memo,
        }
        try:
            user = User.objects.get(username=username)
            if not user.enabled:
                error_message = '用户已禁用!'
                return JsonResponse({"code": 401, "err": error_message})

            setting = json.loads(user.setting)
            k = 0
            for i in setting['clissh']:
                if i['name'] == clissh_name:
                    setting['clissh'][k]['path'] = clissh_path
                    setting['clissh'][k]['args'] = clissh_args
                    setting['clissh'][k]['enable'] = True
                else:
                    setting['clissh'][k]['enable'] = False
                k += 1

            k = 0
            for i in setting['clisftp']:
                if i['name'] == clisftp_name:
                    setting['clisftp'][k]['path'] = clisftp_path
                    setting['clisftp'][k]['args'] = clisftp_args
                    setting['clisftp'][k]['enable'] = True
                else:
                    setting['clisftp'][k]['enable'] = False
                k += 1

            data['setting'] = json.dumps(setting)

            User.objects.filter(pk=userid, username=username).update(**data)
            request.session['nickname'] = nickname
            event_log(user, 10, '用户 [{}] 更新个人信息成功'.format(username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            error_message = '用户不存在!'
            return JsonResponse({"code": 402, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 403, "err": error_message})
Esempio n. 26
0
def group_add(request):
    addgroup_form = AddGroupForm(request.POST)
    if addgroup_form.is_valid():
        log_user = request.session.get('username')
        groupname = addgroup_form.cleaned_data.get('groupname')
        memo = addgroup_form.cleaned_data.get('memo')
        users = addgroup_form.cleaned_data.get('users')
        if users:
            try:
                users = [int(user) for user in users.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            users = None

        hosts = addgroup_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        permissions = addgroup_form.cleaned_data.get('permissions')
        if permissions:
            try:
                permissions = [
                    int(permissions) for permissions in permissions.split(',')
                ]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            permissions = None

        data = {
            'group_name': groupname,
            'memo': memo,
        }

        try:
            if Group.objects.filter(group_name=groupname).count() > 0:
                error_message = '组名已存在'
                return JsonResponse({"code": 402, "err": error_message})
            user = User.objects.get(username=log_user)
            update_group = Group.objects.create(**data)
            if users:  # 更新用户组
                update_users = User.objects.filter(id__in=users)
                update_group.user_set.set(update_users)
            else:
                update_group.user_set.clear()

            if hosts:  # 更新主机多对多字段
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_hosts = RemoteUserBindHost.objects.filter(
                        id__in=hosts)
                else:
                    update_hosts = RemoteUserBindHost.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=hosts).distinct()
                update_group.remote_user_bind_hosts.set(update_hosts)
            else:
                update_group.remote_user_bind_hosts.clear()

            if permissions:
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_permissions = Permission.objects.filter(
                        id__in=permissions)
                else:
                    update_permissions = Permission.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=permissions).distinct()
                update_group.permission.set(update_permissions)
            else:
                update_group.permission.clear()

            update_group.save()
            event_log(user, 8, '组 [{}] 添加成功'.format(update_group.group_name),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '未知错误!'
            return JsonResponse({"code": 403, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 404, "err": error_message})
Esempio n. 27
0
def group_update(request):
    changegroup_form = ChangeGroupForm(request.POST)
    if changegroup_form.is_valid():
        log_user = request.session.get('username')
        groupid = changegroup_form.cleaned_data.get('groupid')
        memo = changegroup_form.cleaned_data.get('memo')
        users = changegroup_form.cleaned_data.get('users')
        if users:
            try:
                users = [int(user) for user in users.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            users = None

        hosts = changegroup_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        permissions = changegroup_form.cleaned_data.get('permissions')
        if permissions:
            try:
                permissions = [
                    int(permissions) for permissions in permissions.split(',')
                ]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            permissions = None

        data = {
            'memo': memo,
        }

        try:
            user = User.objects.get(username=log_user)
            Group.objects.filter(id=groupid).update(**data)
            update_group = Group.objects.get(id=groupid)
            if users:  # 更新用户组
                update_users = User.objects.filter(id__in=users)
                update_group.user_set.set(update_users)
            else:
                update_group.user_set.clear()

            other_hosts = None
            if not request.session[
                    'issuperuser'] or request.session['username'] != 'admin':
                # 修改的组中可能存在拥有的主机但是操作用户没有此主机的情况
                other_hosts = RemoteUserBindHost.objects.filter(
                    Q(group__id=groupid)).filter(
                        ~Q(user__username=request.session['username'])
                        & ~Q(group__user__username=request.session['username'])
                    ).distinct()

            other_permissions = None
            if not request.session[
                    'issuperuser'] or request.session['username'] != 'admin':
                # 修改的组中可能存在拥有的权限但是操作用户没有此权限的情况
                other_permissions = Permission.objects.filter(
                    Q(group__id=groupid)).filter(
                        ~Q(user__username=request.session['username'])
                        & ~Q(group__user__username=request.session['username'])
                    ).distinct()

            if hosts:  # 更新主机多对多字段
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_hosts = RemoteUserBindHost.objects.filter(
                        id__in=hosts)
                else:
                    update_hosts = RemoteUserBindHost.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=hosts).distinct()
                update_group.remote_user_bind_hosts.set(update_hosts)
            else:
                update_group.remote_user_bind_hosts.clear()

            if permissions:
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_permissions = Permission.objects.filter(
                        id__in=permissions)
                else:
                    update_permissions = Permission.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=permissions).distinct()
                update_group.permission.set(update_permissions)
            else:
                update_group.permission.clear()

            if other_hosts:
                for i in other_hosts:
                    update_group.remote_user_bind_hosts.add(i)

            if other_permissions:
                for i in other_permissions:
                    update_group.permission.add(i)

            update_group.save()
            event_log(user, 11,
                      '组 [{}] 更新信息成功'.format(update_group.group_name),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '组不存在!'
            return JsonResponse({"code": 402, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 403, "err": error_message})
Esempio n. 28
0
def user_add(request):
    adduser_form = AddUserForm(request.POST)
    if adduser_form.is_valid():
        log_user = request.session.get('username')
        username = adduser_form.cleaned_data.get('username')
        newpasswd = adduser_form.cleaned_data.get('newpasswd')
        newpasswdagain = adduser_form.cleaned_data.get('newpasswdagain')
        if newpasswd != newpasswdagain:
            error_message = '两次密码不一致!'
            return JsonResponse({"code": 400, "err": error_message})
        nickname = adduser_form.cleaned_data.get('nickname')
        email = adduser_form.cleaned_data.get('email')
        phone = adduser_form.cleaned_data.get('phone')
        weixin = adduser_form.cleaned_data.get('weixin')
        qq = adduser_form.cleaned_data.get('qq')
        sex = adduser_form.cleaned_data.get('sex')
        memo = adduser_form.cleaned_data.get('memo')
        enabled = adduser_form.cleaned_data.get('enabled')
        role = adduser_form.cleaned_data.get('role')
        groups = adduser_form.cleaned_data.get('groups')
        if groups:
            try:
                groups = [int(group) for group in groups.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            groups = None

        hosts = adduser_form.cleaned_data.get('hosts')
        if hosts:
            try:
                hosts = [int(host) for host in hosts.split(',')]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            hosts = None

        permissions = adduser_form.cleaned_data.get('permissions')
        if permissions:
            try:
                permissions = [
                    int(permissions) for permissions in permissions.split(',')
                ]
            except Exception:
                error_message = '请检查填写的内容!'
                return JsonResponse({"code": 401, "err": error_message})
        else:
            permissions = None

        data = {
            'username': username,
            'password': hash_code(newpasswd),
            'nickname': nickname,
            'email': email,
            'phone': phone,
            'weixin': weixin,
            'qq': qq,
            'sex': sex,
            'memo': memo,
            'enabled': enabled,
            'role': role,
        }
        try:
            if User.objects.filter(username=username).count() > 0:
                error_message = '用户名已存在'
                return JsonResponse({"code": 402, "err": error_message})
            user = User.objects.get(username=log_user)
            update_user = User.objects.create(**data)
            if groups:  # 更新组多对多字段
                update_groups = Group.objects.filter(id__in=groups)
                update_user.groups.set(update_groups)
            else:
                update_user.groups.clear()

            if hosts:  # 更新主机多对多字段
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_hosts = RemoteUserBindHost.objects.filter(
                        id__in=hosts)
                else:
                    update_hosts = RemoteUserBindHost.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=hosts).distinct()
                update_user.remote_user_bind_hosts.set(update_hosts)
            else:
                update_user.remote_user_bind_hosts.clear()

            if permissions:
                if request.session['issuperuser'] and request.session[
                        'username'] == 'admin':
                    update_permissions = Permission.objects.filter(
                        id__in=permissions)
                else:
                    update_permissions = Permission.objects.filter(
                        Q(user__username=request.session['username'])
                        | Q(group__user__username=request.session['username']),
                        id__in=permissions).distinct()
                update_user.permission.set(update_permissions)
            else:
                update_user.permission.clear()

            update_user.save()
            event_log(user, 6, '用户 [{}] 添加成功'.format(update_user.username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '未知错误!'
            return JsonResponse({"code": 403, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 404, "err": error_message})
Esempio n. 29
0
def password_update(request):
    changepasswd_form = ChangePasswdForm(request.POST)
    if changepasswd_form.is_valid():
        username = request.session.get('username')
        oldpassword = changepasswd_form.cleaned_data.get('oldpasswd')
        newpasswd = changepasswd_form.cleaned_data.get('newpasswd')
        newpasswdagain = changepasswd_form.cleaned_data.get('newpasswdagain')
        try:
            user = User.objects.get(username=username)
            if not user.enabled:
                error_message = '用户已禁用!'
                event_log(user, 4, '用户 [{}] 已禁用'.format(user.username),
                          request.META.get('REMOTE_ADDR', None),
                          request.META.get('HTTP_USER_AGENT', None))
                return JsonResponse({"code": 401, "err": error_message})
            if newpasswd != newpasswdagain:
                error_message = '两次输入的新密码不一致'
                event_log(user, 4, '两次输入的新密码不一致',
                          request.META.get('REMOTE_ADDR', None),
                          request.META.get('HTTP_USER_AGENT', None))
                return JsonResponse({"code": 400, "err": error_message})
        except Exception:
            error_message = '用户不存在!'
            event_log(None, 4, '用户 [{}] 不存在'.format(username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 403, "err": error_message})
        if user.password == hash_code(oldpassword):
            data = {'password': hash_code(newpasswd)}
            User.objects.filter(username=username).update(**data)
            event_log(user, 5, '用户 [{}] 修改密码成功'.format(user.username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 200, "err": ""})
        else:
            error_message = '当前密码错误!'
            event_log(user, 4, '用户 [{}] 当前密码错误'.format(user.username),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            return JsonResponse({"code": 404, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        user = User.objects.get(username=request.session.get('username'))
        event_log(user, 4, '修改密码表单验证错误', request.META.get('REMOTE_ADDR', None),
                  request.META.get('HTTP_USER_AGENT', None))
        return JsonResponse({"code": 406, "err": error_message})
Esempio n. 30
0
def host_add(request):
    addhost_form = AddHostForm(request.POST)
    if addhost_form.is_valid():
        log_user = request.session.get('username')
        hostname = addhost_form.cleaned_data.get('hostname')
        type = addhost_form.cleaned_data.get('type')
        ip = addhost_form.cleaned_data.get('ip')
        wip = addhost_form.cleaned_data.get('wip')
        protocol = addhost_form.cleaned_data.get('protocol')
        env = addhost_form.cleaned_data.get('env')
        platform = addhost_form.cleaned_data.get('platform')
        port = addhost_form.cleaned_data.get('port')
        release = addhost_form.cleaned_data.get('release')
        memo = addhost_form.cleaned_data.get('memo')
        enabled = addhost_form.cleaned_data.get('enabled')
        binduserid = addhost_form.cleaned_data.get('binduserid')
        data = {
            'hostname': hostname,
            'type': type,
            'ip': ip,
            'wip': wip,
            'protocol': protocol,
            'env': env,
            'platform': platform,
            'port': port,
            'release': release,
            'memo': memo,
            'enabled': enabled,
        }
        try:
            user = User.objects.get(username=log_user)
            remoteuser = RemoteUser.objects.get(id=binduserid)
            data['remote_user'] = remoteuser
            remoteuserbindhost = RemoteUserBindHost.objects.create(**data)
            if not request.session[
                    'issuperuser'] or request.session['username'] != 'admin':
                user.remote_user_bind_hosts.add(
                    remoteuserbindhost)  #  非 admin 添加的主机分配给自己
            event_log(user, 12,
                      '主机 [{}] 添加成功'.format(remoteuserbindhost.hostname),
                      request.META.get('REMOTE_ADDR', None),
                      request.META.get('HTTP_USER_AGENT', None))
            hostinfo = dict()
            hostinfo['id'] = remoteuserbindhost.id
            hostinfo['hostname'] = remoteuserbindhost.hostname
            hostinfo['ip'] = remoteuserbindhost.ip
            hostinfo['port'] = remoteuserbindhost.port
            hostinfo['platform'] = remoteuserbindhost.get_platform_display()
            hostinfo['username'] = remoteuserbindhost.remote_user.username
            hostinfo['password'] = remoteuserbindhost.remote_user.password
            if remoteuserbindhost.remote_user.enabled:
                hostinfo[
                    'superusername'] = remoteuserbindhost.remote_user.superusername
                hostinfo[
                    'superpassword'] = remoteuserbindhost.remote_user.superpassword
            else:
                hostinfo['superusername'] = None
            task_host_update_info.delay(hostinfo=hostinfo)
            return JsonResponse({"code": 200, "err": ""})
        except Exception:
            # print(traceback.format_exc())
            error_message = '未知错误!'
            return JsonResponse({"code": 400, "err": error_message})
    else:
        error_message = '请检查填写的内容!'
        return JsonResponse({"code": 401, "err": error_message})