Esempio n. 1
0
def article_tag(request, pid):
    try:
        tag = Tag.objects.get(id=pid)
    except Exception, ex:
        logger.warn(msg="标签不存在: {ex}".format(ex=ex))
        return render(request, 'wiki/wiki_base.html', {
            "user": request.user,
            "errorInfo": "标签不存在: {ex}".format(ex=ex)
        })
Esempio n. 2
0
def article_category(request, pid):
    try:
        category = Category.objects.get(id=pid)
    except Exception, ex:
        logger.warn(msg="分类不存在: {ex}".format(ex=ex))
        return render(request, 'wiki/wiki_base.html', {
            "user": request.user,
            "errorInfo": "分类不存在: {ex}".format(ex=ex)
        })
Esempio n. 3
0
def assets_view(request, aid):
    try:
        assets = Assets.objects.get(id=aid)
        userList = User.objects.all()
    except:
        return render(
            request,
            '404.html',
            {"user": request.user},
        )
    if assets.assets_type in ['server', 'vmser']:
        try:
            asset_ram = assets.ram_assets_set.all()
        except:
            asset_ram = []
        try:
            asset_disk = assets.disk_assets_set.all()
        except:
            asset_disk = []
        try:
            asset_nks = assets.networkcard_assets_set.all()
        except Exception, ex:
            asset_nks = []
            logger.warn(msg="获取网卡设备资产失败: {ex}".format(ex=str(ex)))
        try:
            asset_body = assets.server_assets
        except:
            return render(
                request,
                'assets/assets_view.html',
                {"user": request.user},
            )
        return render(
            request,
            'assets/assets_view.html',
            {
                "user": request.user,
                "asset_type": assets.assets_type,
                "asset_main": assets,
                "asset_body": asset_body,
                "asset_ram": asset_ram,
                "asset_disk": asset_disk,
                "baseAssets": getBaseAssets(),
                'userList': userList,
                "asset_nks": asset_nks
            },
        )
Esempio n. 4
0
def task_view(request):
    if request.method == "GET":
        try:
            workList = WorkerState.objects.all()
            regTaskList = []
            for task in list(keys(cTasks)):
                if task.startswith('OMBA.tasks.ansible') or task.startswith(
                        'OMBA.tasks.sched'):
                    regTaskList.append(task)
        except Exception, ex:
            logger.warn(msg="获取Celery Task失败: {ex}".format(ex=str(ex)))
            taskLog = []
        return render(
            request,
            'task/task_view.html',
            {
                "user": request.user,
                "regTaskList": regTaskList,
                "workList": workList
            },
        )
Esempio n. 5
0
def article_add(request):
    if request.method == "GET":
        tagList = Tag.objects.all()
        categoryList = Category.objects.all()
        return render(request, 'wiki/wiki_post.html', {
            "user": request.user,
            "tagList": tagList,
            "categoryList": categoryList
        })
    elif request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        tags = request.POST.getlist('tag[]')
        try:
            category = Category.objects.get(id=category)
        except Exception, ex:
            logger.warn(msg="获取分类失败: {ex}".format(ex=str(ex)))
            return JsonResponse({
                'msg': "获取分类失败: {ex}".format(ex=str(ex)),
                "code": 500,
                'data': []
            })
        try:
            article = Post.objects.create(
                title=title,
                content=content,
                category=category,
                author=User.objects.get(username=request.user))
        except Exception, ex:
            logger.warn(msg="创建文章失败: {ex}".format(ex=str(ex)))
            return JsonResponse({
                'msg': "创建文章失败: {ex}".format(ex=str(ex)),
                "code": 500,
                'data': []
            })
Esempio n. 6
0
def assets_batch(request):
    if request.method == "POST":
        fList = []
        sList = []
        resource = []
        serList = []
        if request.POST.get('model') == 'update':
            for ast in request.POST.getlist('assetsIds[]'):
                try:
                    assets = Assets.objects.get(id=int(ast))
                except Exception, ex:
                    logger.warn(msg="批量更新获取资产失败: {ex}".format(ex=str(ex)))
                    continue
                if assets.assets_type in ['vmser', 'server']:
                    try:
                        server_assets = Server_Assets.objects.get(
                            assets=assets)
                    except Exception, ex:
                        logger.warn(msg="批量更新获取服务器资产失败: {ex}".format(
                            ex=str(ex)))
                        if server_assets.ip not in fList:
                            fList.append(server_assets.ip)
                        continue
                    serList.append(server_assets.ip)
                    if server_assets.keyfile == 1:
                        resource.append({
                            "hostname": server_assets.ip,
                            "port": int(server_assets.port),
                            "username": server_assets.username
                        })
                    else:
                        resource.append({
                            "hostname": server_assets.ip,
                            "port": server_assets.port,
                            "username": server_assets.username,
                            "password": server_assets.passwd
                        })
            ANS = ANSRunner(resource)
            ANS.run_model(host_list=serList,
                          module_name='setup',
                          module_args="")
            data = ANS.handle_cmdb_data(ANS.get_model_result())
            if data:
                for ds in data:
                    status = ds.get('status')
                    sip = ds.get('ip')
                    if status == 0:
                        assets = Server_Assets.objects.get(
                            ip=ds.get('ip')).assets
                        assets.model = ds.get('model')
                        assets.save()
                        try:
                            Server_Assets.objects.filter(
                                ip=ds.get('ip')).update(
                                    cpu_number=ds.get('cpu_number'),
                                    kernel=ds.get('kernel'),
                                    selinux=ds.get('selinux'),
                                    hostname=ds.get('hostname'),
                                    system=ds.get('system'),
                                    cpu=ds.get('cpu'),
                                    disk_total=ds.get('disk_total'),
                                    cpu_core=ds.get('cpu_core'),
                                    swap=ds.get('swap'),
                                    ram_total=ds.get('ram_total'),
                                    vcpu_number=ds.get('vcpu_number'))
                            if sip not in sList:
                                sList.append(sip)
                        except Exception:
                            if sip not in fList:
                                fList.append(sip)
                        for nk in ds.get('nks'):
                            macaddress = nk.get('macaddress')
                            count = NetworkCard_Assets.objects.filter(
                                assets=assets, macaddress=macaddress).count()
                            if count > 0:
                                try:
                                    NetworkCard_Assets.objects.filter(
                                        assets=assets,
                                        macaddress=macaddress).update(
                                            assets=assets,
                                            device=nk.get('device'),
                                            ip=nk.get('address'),
                                            module=nk.get('module'),
                                            mtu=nk.get('mtu'),
                                            active=nk.get('active'))
                                except Exception, ex:
                                    logger.warn(
                                        msg="批量更新更新服务器网卡资产失败: {ex}".format(
                                            ex=str(ex)))
                            else:
                                try:
                                    NetworkCard_Assets.objects.create(
                                        assets=assets,
                                        device=nk.get('device'),
                                        macaddress=nk.get('macaddress'),
                                        ip=nk.get('address'),
                                        module=nk.get('module'),
                                        mtu=nk.get('mtu'),
                                        active=nk.get('active'))
                                except Exception, ex:
                                    logger.warn(
                                        msg="批量更新写入服务器网卡资产失败: {ex}".format(
                                            ex=str(ex)))
                    else:
                        if sip not in fList:
                            fList.append(sip)
Esempio n. 7
0
def assets_import(request):
    if request.method == "POST":
        f = request.FILES.get('import_file')
        filename = os.path.join(os.getcwd() + '/upload/', f.name)
        if os.path.isdir(os.path.dirname(filename)) is not True:
            os.makedirs(os.path.dirname(filename))
        fobj = open(filename, 'wb')
        for chrunk in f.chunks():
            fobj.write(chrunk)
        fobj.close()

        # 读取上传的execl文件内容方法
        def getAssetsData(fname=filename):
            bk = xlrd.open_workbook(fname)
            dataList = []
            try:
                server = bk.sheet_by_name("server")
                net = bk.sheet_by_name("net")
                for i in range(1, server.nrows):
                    dataList.append(server.row_values(i))
                for i in range(1, net.nrows):
                    dataList.append(net.row_values(i))
            except Exception, e:
                return []
            return dataList

        dataList = getAssetsData(fname=filename)
        # 获取服务器列表
        for data in dataList:
            assets = {
                'assets_type': data[0],
                'name': data[1],
                'sn': data[2],
                'buy_user': int(data[5]),
                'management_ip': data[6],
                'manufacturer': data[7],
                'model': data[8],
                'provider': data[9],
                'status': int(data[10]),
                'put_zone': int(data[11]),
                'group': int(data[12]),
                'project': int(data[13]),
                'business': int(data[14]),
            }
            if data[3]:
                assets['buy_time'] = xlrd.xldate.xldate_as_datetime(data[3], 0)
            if data[4]:
                assets['expire_date'] = xlrd.xldate.xldate_as_datetime(
                    data[4], 0)
            if assets.get('assets_type') in ['vmser', 'server']:
                server_assets = {
                    'ip': data[15],
                    'keyfile': data[16],
                    'username': data[17],
                    'passwd': data[18],
                    'hostname': data[19],
                    'port': data[20],
                    'raid': data[21],
                    'line': data[22],
                }
            else:
                net_assets = {
                    'ip': data[15],
                    'bandwidth': data[16],
                    'port_number': data[17],
                    'firmware': data[18],
                    'cpu': data[19],
                    'stone': data[20],
                    'configure_detail': data[21]
                }
            count = Assets.objects.filter(name=assets.get('name')).count()
            if count == 1:
                assetsObj = Assets.objects.get(name=assets.get('name'))
                Assets.objects.filter(name=assets.get('name')).update(**assets)
                try:
                    if assets.get('assets_type') in ['vmser', 'server']:
                        Server_Assets.objects.filter(assets=assetsObj).update(
                            **server_assets)
                    elif assets.get('assets_type') in [
                            'switch', 'route', 'printer', 'scanner',
                            'firewall', 'storage', 'wifi'
                    ]:
                        Network_Assets.objects.filter(assets=assetsObj).update(
                            **net_assets)
                except Exception, ex:
                    print ex
            else:
                try:
                    assetsObj = Assets.objects.create(**assets)
                except Exception, ex:
                    logger.warn(msg="批量写入资产失败: {ex}".format(ex=str(ex)))
                if assetsObj:
                    try:
                        if assets.get('assets_type') in ['vmser', 'server']:
                            Server_Assets.objects.create(assets=assetsObj,
                                                         **server_assets)
                        elif assets.get('assets_type') in [
                                'switch', 'route', 'printer', 'scanner',
                                'firewall', 'storage', 'wifi'
                        ]:
                            Network_Assets.objects.create(assets=assetsObj,
                                                          **net_assets)
                    except Exception, ex:
                        logger.warn(msg="批量更新资产失败: {ex}".format(ex=str(ex)))
                        assetsObj.delete()
Esempio n. 8
0
def assets_facts(request, args=None):
    if request.method == "POST" and request.user.has_perm(
            'OMBA.change_server_assets'):
        server_id = request.POST.get('server_id')
        genre = request.POST.get('type')
        if genre == 'setup':
            try:
                server_assets = Server_Assets.objects.get(
                    id=request.POST.get('server_id'))
                if server_assets.keyfile == 1:
                    resource = [{
                        "hostname": server_assets.ip,
                        "port": int(server_assets.port),
                        "username": server_assets.username
                    }]
                else:
                    resource = [{
                        "hostname": server_assets.ip,
                        "port": server_assets.port,
                        "username": server_assets.username,
                        "password": server_assets.passwd
                    }]
            except Exception, ex:
                logger.error(msg="更新资产失败: {ex}".format(ex=str(ex)))
                return JsonResponse({'msg': "数据更新失败-查询不到该主机资料", "code": 502})
            ANS = ANSRunner(resource)
            ANS.run_model(host_list=[server_assets.ip],
                          module_name='setup',
                          module_args="")
            data = ANS.handle_cmdb_data(ANS.get_model_result())
            if data:
                for ds in data:
                    status = ds.get('status')
                    if status == 0:
                        try:
                            assets = Assets.objects.get(
                                id=server_assets.assets_id)
                            Assets.objects.filter(
                                id=server_assets.assets_id).update(
                                    sn=ds.get('serial'),
                                    model=ds.get('model'),
                                    manufacturer=ds.get('manufacturer'))
                        except Exception, ex:
                            logger.error(msg="获取服务器信息失败: {ex}".format(
                                ex=str(ex)))
                            return JsonResponse({
                                'msg': "数据更新失败-查询不到该主机的资产信息",
                                "code": 403
                            })
                        try:
                            Server_Assets.objects.filter(id=server_id).update(
                                cpu_number=ds.get('cpu_number'),
                                kernel=ds.get('kernel'),
                                selinux=ds.get('selinux'),
                                hostname=ds.get('hostname'),
                                system=ds.get('system'),
                                cpu=ds.get('cpu'),
                                disk_total=ds.get('disk_total'),
                                cpu_core=ds.get('cpu_core'),
                                swap=ds.get('swap'),
                                ram_total=ds.get('ram_total'),
                                vcpu_number=ds.get('vcpu_number'))
                            recordAssets.delay(user=str(request.user),
                                               content="修改服务器资产:{ip}".format(
                                                   ip=server_assets.ip),
                                               type="server",
                                               id=server_assets.id)
                        except Exception, ex:
                            logger.error(msg="更新服务器信息失败: {ex}".format(
                                ex=str(ex)))
                            return JsonResponse({
                                'msg': "数据更新失败-写入数据失败",
                                "code": 400
                            })
                        for nk in ds.get('nks'):
                            macaddress = nk.get('macaddress')
                            count = NetworkCard_Assets.objects.filter(
                                assets=assets, macaddress=macaddress).count()
                            if count > 0:
                                try:
                                    NetworkCard_Assets.objects.filter(
                                        assets=assets,
                                        macaddress=macaddress).update(
                                            assets=assets,
                                            device=nk.get('device'),
                                            ip=nk.get('address'),
                                            module=nk.get('module'),
                                            mtu=nk.get('mtu'),
                                            active=nk.get('active'))
                                except Exception, ex:
                                    logger.warn(msg="更新服务器网卡信息失败: {ex}".format(
                                        ex=str(ex)))
                            else:
                                try:
                                    NetworkCard_Assets.objects.create(
                                        assets=assets,
                                        device=nk.get('device'),
                                        macaddress=nk.get('macaddress'),
                                        ip=nk.get('address'),
                                        module=nk.get('module'),
                                        mtu=nk.get('mtu'),
                                        active=nk.get('active'))
                                except Exception, ex:
                                    logger.warn(msg="写入服务器网卡信息失败: {ex}".format(
                                        ex=str(ex)))
Esempio n. 9
0
             data['name'] = task[taskLog.name]
         else:
             data['name'] = taskLog.name
         data['tstamp'] = taskLog.tstamp
         data['args'] = taskLog.args.replace('[u', '[')
         data['kwargs'] = taskLog.kwargs.replace('u\'', '\'')
         data['result'] = taskLog.result
         data['state'] = taskLog.state
         data['runtime'] = taskLog.runtime
         return JsonResponse({
             "code": 200,
             "data": data,
             "msg": "操作成功"
         })
     except Exception, ex:
         logger.warn(msg="查看Celery Task运行日志失败: {ex}".format(
             ex=str(ex)))
         return JsonResponse({
             "code": 500,
             "data": None,
             "msg": "日志查看失败。"
         })
 elif op == 'delete':
     try:
         taskLog.delete()
         return JsonResponse({
             "code": 200,
             "data": None,
             "msg": "删除成功"
         })
     except:
         return JsonResponse({
Esempio n. 10
0
                content=content,
                category=category,
                author=User.objects.get(username=request.user))
        except Exception, ex:
            logger.warn(msg="创建文章失败: {ex}".format(ex=str(ex)))
            return JsonResponse({
                'msg': "创建文章失败: {ex}".format(ex=str(ex)),
                "code": 500,
                'data': []
            })
        try:
            for tg in tags:
                tag = Tag.objects.get(id=tg)
                article.tags.add(tag)
        except Exception, ex:
            logger.warn(msg="创建文章标签失败: {ex}".format(ex=str(ex)))
        return JsonResponse({'msg': "文章添加成功", "code": 200, 'data': []})


@login_required()
@csrf_exempt
def upload_image(request):
    if request.method == 'POST':
        f = request.FILES["upload"]
        callback = request.GET.get('CKEditorFuncNum', '1')
        if f:
            try:
                datePath = time.strftime("%Y/%m/%d/", time.localtime())
                path = os.getcwd() + "/upload/wiki/" + datePath
                filePath = path + f.name
                if os.path.isdir(os.path.dirname(filePath)) is not True: