示例#1
0
    def post(request):
        """
        执行工具
        :param request:  asset_id,tool_id
        :return:  ret
        """
        ret = {
            'status': True,
            'error': None,
        }
        name = Names.objects.get(username=request.user)
        try:
            asset_id = request.POST.getlist('asset[]', None)
            tool_id = request.POST.getlist('tool[]', None)

            if asset_id == [] or tool_id == []:
                ret['status'] = False
                ret['error'] = '未选择主机 或 未选择工具'
                return HttpResponse(json.dumps(ret))

            asset_id_tring = ','.join(asset_id)

            asset_obj = AssetInfo.objects.extra(
                where=['id IN (' + asset_id_tring + ')'])

            for i in asset_obj:
                pro = AssetInfo.objects.get(hostname=i).project
                proj = AssetProject.objects.get(projects=pro)
                rets = name.has_perm('cmd_assetproject', proj)
                if rets == False:
                    return HttpResponse(status=403)

            tool_obj = Tools.objects.filter(id=int(tool_id[0])).first()
            assets = []
            for i in asset_obj:
                varall = {
                    'hostname': i.hostname,
                    'inner_ip': i.inner_ip,
                    "network_ip": i.network_ip,
                    "project": i.project.projects
                }
                try:
                    varall.update(
                        Variable.objects.get(assets__hostname=i).vars)
                except Exception as e:
                    logger.error(e)

                assets.append(
                    {
                        "hostname": i.hostname,
                        "ip": i.network_ip,
                        "port": i.port,
                        "username": i.user.username,
                        "password": decrypt_p(i.user.password),
                        "private_key": i.user.private_key.name,
                        "vars": varall,
                    }, )

            file = "data/script/{0}".format(random.randint(0, 999999))
            file2 = "data/script/{0}".format(random.randint(1000000, 9999999))
            rets = None
            if tool_obj.tool_run_type == 'shell' or tool_obj.tool_run_type == 'python':

                with open("{}.sh".format(file), 'w+') as f:
                    f.write(tool_obj.tool_script)
                os.system("sed  's/\r//'  {0}.sh >  {1}.sh".format(
                    file, file2))
                rets = ansbile_tools.delay(assets, '{}.sh'.format(file2),
                                           "script")
            elif tool_obj.tool_run_type == 'yml':

                with open("{}.yml".format(file), 'w+') as f:
                    f.write(tool_obj.tool_script)
                os.system("sed  's/\r//'  {0}.yml >  {1}.yml".format(
                    file, file2))
                rets = ansbile_tools.delay(assets,
                                           tools='{}.yml'.format(file2),
                                           modules="yml")

            task_obj = ToolsResults.objects.create(task_id=rets.task_id)
            ret['id'] = task_obj.id
            return HttpResponse(json.dumps(ret))
        except Exception as e:
            ret['status'] = False
            ret['error'] = '创建任务失败,{0}'.format(e)
            return HttpResponse(json.dumps(ret))
示例#2
0
    def post(self, request):
        """
        执行工具
        :param request:  asset_id,tool_id
        :return:  ret
        """
        ret = {
            'status': True,
            'error': None,
        }

        try:
            asset_id = request.POST.getlist('asset[]', None)
            tool_id = request.POST.getlist('tool[]', None)

            if asset_id == [] or tool_id == []:
                ret['status'] = False
                ret['error'] = '未选择主机 或 未选择工具'
                return HttpResponse(json.dumps(ret))

            asset_id_tring = ','.join(asset_id)

            asset_obj = asset.objects.extra(
                where=['id IN (' + asset_id_tring + ')'])
            tool_obj = tools_script.objects.filter(id=int(tool_id[0])).first()

            assets = []

            for i in asset_obj:
                assets.append(
                    [{
                        "hostname": i.hostname,
                        "ip": i.network_ip,
                        "port": i.port,
                        "username": i.user.username,
                        "password": decrypt_p(i.user.password),
                        "private_key": i.user.private_key.name,
                        # "vars": {'name':123}, 变量
                    }], )

            file = "data/script/{0}".format(random.randint(0, 999999))
            file2 = "data/script/{0}".format(random.randint(1000000, 9999999))

            if tool_obj.tool_run_type == 'shell' or tool_obj.tool_run_type == 'python':

                with open("{}.sh".format(file), 'w+') as f:
                    f.write(tool_obj.tool_script)
                os.system("sed  's/\r//'  {0}.sh >  {1}.sh".format(
                    file, file2))
                rets = ansbile_tools.delay(assets, '{}.sh'.format(file2),
                                           "script")
            elif tool_obj.tool_run_type == 'yml':

                with open("{}.yml".format(file), 'w+') as f:
                    f.write(tool_obj.tool_script)
                os.system("sed  's/\r//'  {0}.yml >  {1}.yml".format(
                    file, file2))
                rets = ansbile_tools.delay(assets, '{}.yml'.format(file2),
                                           "yml")

            task_obj = tool_results.objects.create(task_id=rets.task_id)
            ret['id'] = task_obj.id

        except Exception as e:
            ret['status'] = False
            ret['error'] = '创建任务失败,{0}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret))
示例#3
0
    def post(request):
        """
        执行工具
        :param request:  asset_id,tool_id,priority
        :return:  ret
        """
        ret = {
            'status': True,
            'error': None,
        }
        name = Names.objects.get(username=request.user)
        try:
            asset_id = request.POST.getlist('asset_id', None)
            tool_id = request.POST.getlist('tool_id', None)
            priority = request.POST.getlist('priority', None)

            if asset_id == [] or tool_id == [] or priority == []:
                ret['status'] = False
                ret['error'] = '未选择主机 或 未选择脚本 或 未设置优先级'
                return HttpResponse(json.dumps(ret))

            while '' in priority:
                priority.remove('')

            for i in priority:
                if priority.count(i) >= 2:
                    ret['status'] = False
                    ret['error'] = '优先级设置有重复 ,请重新修改!!!'
                    return HttpResponse(json.dumps(ret))

            asset_id_tring = ','.join(asset_id)
            asset_obj = AssetInfo.objects.extra(
                where=['id IN (' + asset_id_tring + ')'])

            for i in asset_obj:
                project = AssetInfo.objects.get(hostname=i).project
                project_obj = AssetProject.objects.get(projects=project)
                hasperm = name.has_perm('cmd_assetproject', project_obj)
                if not hasperm:
                    return HttpResponse(status=500)

            assets = []
            for i in asset_obj:
                var_all = {
                    'hostname': i.hostname,
                    'inner_ip': i.inner_ip,
                    "network_ip": i.network_ip,
                    "project": i.project.projects
                }
                try:
                    var_all.update(
                        Variable.objects.get(assets__hostname=i).vars)
                except Exception as e:
                    pass

                assets.append(
                    {
                        "hostname": i.hostname,
                        "ip": i.network_ip,
                        "port": i.port,
                        "username": i.user.username,
                        "password": decrypt_p(i.user.password),
                        "private_key": i.user.private_key.name,
                        "vars": var_all,
                    }, )

            tool_priority_1 = dict(zip(tool_id, priority))
            tool_priority = sorted(tool_priority_1.items(),
                                   key=lambda item: item[1])

            tasks = []
            for i in tool_priority:
                tool_obj = Tools.objects.get(id=i[0])
                if tool_obj.tool_run_type == 'shell' or tool_obj.tool_run_type == 'python':
                    t = time.time()
                    file = "data/script/{0}".format(
                        int(round(t * 1000)) + random.randint(0, 999999))
                    t1 = time.time()
                    file2 = "data/script/{0}".format(
                        int(round(t1 * 1000)) +
                        random.randint(10000000, 99999999))
                    with open("{}.sh".format(file), 'w+') as f:
                        f.write(tool_obj.tool_script)
                    os.system("sed  's/\r//'  {0}.sh >  {1}.sh".format(
                        file, file2))
                    tasks.append(
                        {
                            "action": {
                                "module": "script",
                                "args": '{}.sh'.format(file2),
                            },
                            "name": 'task{}'.format(i[1])
                        }, )

                elif tool_obj.tool_run_type == 'yml':
                    t = time.time()
                    file = "data/script/{0}".format(
                        int(round(t * 1000)) + random.randint(0, 999999))
                    t1 = time.time()
                    file2 = "data/script/{0}".format(
                        int(round(t1 * 1000)) +
                        random.randint(10000000, 99999999))
                    with open("{}.yml".format(file), 'w+') as f:
                        f.write(tool_obj.tool_script)
                    os.system("sed  's/\r//'  {0}.yml >  {1}.yml".format(
                        file, file2))
                    tasks.append(
                        {
                            "action": {
                                "module": "yml",
                                "args": '{}.yml'.format(file2),
                            },
                            "name": 'task{}'.format(i[1])
                        }, )

            rets = ansbile_tools.delay(assets, tasks)
            task_obj = ToolsResults.objects.create(task_id=rets.task_id,
                                                   add_user=name)
            ret['id'] = task_obj.id
            return HttpResponse(json.dumps(ret))
        except Exception as e:
            ret['status'] = False
            ret['error'] = '创建任务失败,{0}'.format(e)
            return HttpResponse(json.dumps(ret))
示例#4
0
文件: views.py 项目: zhaizhifen/chain
    def post(request):
        """
        执行工具
        :param request:  asset_id,tool_id,priority
        :return:  ret
        """
        ret = {'status': True, 'error': None, }
        name = Names.objects.get(username=request.user)
        try:
            asset_id = request.POST.getlist('asset_id', None)
            tool_id = request.POST.getlist('tool_id', None)
            priority = request.POST.getlist('priority', None)
            if asset_id == [] or tool_id == [] or priority == ['']:
                ret['status'] = False
                ret['error'] = '未选择主机 或 未选择脚本 或 未设置优先级'
                return HttpResponse(json.dumps(ret))

            for i in priority:
                if priority.count(i) >= 2:
                    ret['status'] = False
                    ret['error'] = '优先级设置有重复 ,请重新修改!!!'
                    return HttpResponse(json.dumps(ret))

            asset_id_tring = ','.join(asset_id)
            asset_obj = AssetInfo.objects.extra(where=['id IN (' + asset_id_tring + ')'])

            for i in asset_obj:
                project = AssetInfo.objects.get(hostname=i).project
                project_obj = AssetProject.objects.get(projects=project)
                hasperm = name.has_perm('cmd_assetproject', project_obj)
                if not hasperm:
                    return HttpResponse(status=500)

            assets = []
            for i in asset_obj:
                var_all = {
                    'hostname': i.hostname,
                    'inner_ip': i.inner_ip,
                    "network_ip": i.network_ip,
                    "project": i.project.projects
                }
                try:
                    var_all.update(Variable.objects.get(assets__hostname=i).vars)
                except Exception as e:
                    pass

                assets.append({
                    "hostname": i.hostname,
                    "ip": i.network_ip,
                    "port": i.port,
                    "username": i.user.username,
                    "password": decrypt_p(i.user.password),
                    "private_key": i.user.private_key.name,
                    "vars": var_all,
                }, )

            tool_priority_1 = dict(zip(tool_id, priority))
            tool_priority = sorted(tool_priority_1.items(), key=lambda item: item[1])

            tasks = []
            for i in tool_priority:
                tool_obj = Tools.objects.get(id=i[0])
                if tool_obj.tool_run_type == 'shell' or tool_obj.tool_run_type == 'python':
                    t = time.time()
                    file = "data/script/{0}".format(int(round(t * 1000)) + random.randint(0, 999999))
                    t1 = time.time()
                    file2 = "data/script/{0}".format(int(round(t1 * 1000)) + random.randint(10000000, 99999999))
                    with open("{}.sh".format(file), 'w+') as f:
                        f.write(tool_obj.tool_script)
                    os.system("sed  's/\r//'  {0}.sh >  {1}.sh".format(file, file2))
                    tasks.append({"action": {"module": "script", "args": '{}.sh'.format(file2), },
                                  "name": 'task{}'.format(i[1])}, )

                elif tool_obj.tool_run_type == 'yml':
                    t = time.time()
                    file = "data/script/{0}".format(int(round(t * 1000)) + random.randint(0, 999999))
                    t1 = time.time()
                    file2 = "data/script/{0}".format(int(round(t1 * 1000)) + random.randint(10000000, 99999999))
                    with open("{}.yml".format(file), 'w+') as f:
                        f.write(tool_obj.tool_script)
                    os.system("sed  's/\r//'  {0}.yml >  {1}.yml".format(file, file2))
                    tasks.append({"action": {"module": "yml", "args": '{}.yml'.format(file2), },
                                  "name": 'task{}'.format(i[1])}, )

            rets = ansbile_tools.delay(assets, tasks)
            task_obj = ToolsResults.objects.create(task_id=rets.task_id, add_user=name)
            ret['id'] = task_obj.id
            return HttpResponse(json.dumps(ret))
        except Exception as e:
            ret['status'] = False
            ret['error'] = '创建任务失败,{0}'.format(e)
            return HttpResponse(json.dumps(ret))