예제 #1
0
def get_playbook_res(group_ids, playbook_file):
    resource = GenResource().gen_group_dict(group_ids)

    ans = ANSRunner(resource)
    ans.run_playbook(playbook_file)
    res = ans.get_playbook_result()
    return res
예제 #2
0
    def run_playbook(self, group_ids, playbook_id):
        playbook = AnsiblePlaybook.objects.select_related('playbook_user').get(
            id=playbook_id)
        unique_key = '{}.{}'.format(playbook.playbook_name, group_ids)

        if self.redis_instance.get(unique_key):
            self.send(
                '<code style="color: #FF0000">\n有相同的任务正在进行!请稍后重试!\n</code>',
                close=True)
        else:
            try:
                self.redis_instance.set(unique_key, 1)
                resource = GenResource().gen_group_dict(group_ids)

                ans = ANSRunner(resource, sock=self)
                ans.run_playbook(playbook.playbook_file.path)

                playbook_record.delay(
                    playbook_user=UserProfile.objects.get(
                        id=self.ans_info['run_user']),
                    playbook_remote_ip=self.ans_info['remote_ip'],
                    playbook_name=playbook.playbook_name,
                    playbook_result=ans.get_playbook_results)
            except Exception as e:
                self.send(
                    '<code style="color: #FF0000">\nansible执行playbook出错:{}\n</code>'
                    .format(str(e)))
            finally:
                self.redis_instance.delete(unique_key)
                self.close()
예제 #3
0
    def run_model(self, group_ids, host_ids, selected_module_name, custom_model_name, module_args):
        gen_resource = GenResource()

        if group_ids == ['custom'] or group_ids == ['all']:
            resource = gen_resource.gen_host_list(host_ids)
        else:
            resource = gen_resource.gen_group_dict(group_ids)

        host_list = [ServerAssets.objects.get(id=host_id).assets.asset_management_ip for host_id in host_ids]

        module_name = selected_module_name if selected_module_name != 'custom' else custom_model_name

        unique_key = '{}.{}.{}'.format(host_ids, module_name, module_args)

        if self.redis_instance.get(unique_key):
            self.send('<code style="color: #FF0000">\n有相同的任务正在进行!请稍后重试!\n</code>', close=True)
        else:
            try:
                self.redis_instance.set(unique_key, 1)
                ans = ANSRunner(resource, become='yes', become_method='sudo', become_user='******', sock=self)
                ans.run_module(host_list=host_list, module_name=module_name, module_args=module_args)

                module_record.delay(ans_user=UserProfile.objects.get(id=self.ans_info['run_user']),
                                    ans_remote_ip=self.ans_info['remote_ip'],
                                    ans_module=module_name,
                                    ans_args=module_args,
                                    ans_server=host_list, ans_result=ans.get_module_results)
            except Exception as e:
                self.send('<code style="color: #FF0000">\nansible执行模块出错:{}\n</code>'.format(str(e)))
            finally:
                self.redis_instance.delete(unique_key)
                self.close()
예제 #4
0
파일: views.py 프로젝트: ronghuaihai/Ops
def get_playbook_res(group_ids, playbook_file):
    host_ids = None
    for group_id in group_ids:
        inventory_obj = AnsibleInventory.objects.prefetch_related(
            'ans_group_hosts').get(id=group_id)
        hosts = inventory_obj.ans_group_hosts.all()
        host_ids = [host.id for host in hosts]
    host_ids = list(set(host_ids))
    resource = gen_resource(host_ids, group_ids)

    ans = ANSRunner(resource)
    ans.run_playbook(playbook_file)
    res = ans.get_playbook_result()
    return res
예제 #5
0
파일: views.py 프로젝트: zhoujianqi/Ops
def fort_server(request):
    fort_servers = FortServer.objects.select_related('server')
    black_commands, created = FortBlackCommand.objects.get_or_create(id=1)
    fort_users = FortServerUser.objects.select_related('fort_server')
    if request.method == 'POST':
        try:
            new_black_commands = request.POST.get('black_commands')

            if fort_users.count() > 0:

                old_format_commands = format_commands(
                    black_commands.black_commands)
                new_format_commands = format_commands(new_black_commands)

                for fort_server_obj in fort_servers:
                    sudo_users = [
                        user.fort_username
                        for user in fort_server_obj.fortserveruser_set.all()
                    ]

                    resource = GenResource().gen_host_list(
                        list(str(fort_server_obj.server.id)))
                    ans = ANSRunner(resource)
                    ans.run_module(
                        host_list=fort_server_obj.server.assets.
                        asset_management_ip,
                        module_name='shell',
                        module_args=
                        r"cd /etc/sudoers.d/ && sed -i 's@{}@{}@' {}".format(
                            old_format_commands, new_format_commands,
                            ' '.join(sudo_users)))
                    FortBlackCommand.objects.filter(id=1).update(
                        black_commands=new_black_commands)
                    return JsonResponse({'code': 200, 'msg': '更新成功!'})
            else:
                FortBlackCommand.objects.filter(id=1).update(
                    black_commands=new_black_commands)
                return JsonResponse({'code': 200, 'msg': '更新成功!'})
        except Exception as e:
            return JsonResponse({'code': 500, 'msg': '更新失败!:{}'.format(e)})

    hosts = ServerAssets.objects.select_related('assets')
    server_protocols = FortServer.server_protocols
    server_status = FortServer.server_status_
    fort_user_status = FortServerUser.fort_user_status_
    users = UserProfile.objects.all()
    groups = Group.objects.all()
    remote_ip = request.META['REMOTE_ADDR']
    return render(request, 'fort/fort_server.html', locals())
예제 #6
0
def run_module(request):
    if request.method == 'POST':
        gen_resource = GenResource()
        redis_conn = RedisOps(settings.REDIS_HOST, settings.REDIS_PORT,
                              settings.REDIS_DB)
        remote_ip = request.META['REMOTE_ADDR']
        group_ids = request.POST.getlist('hostGroup')
        host_ids = request.POST.getlist('ans_group_hosts')
        if group_ids == ['custom'] or group_ids == ['all']:
            resource = gen_resource.gen_host_list(host_ids)
        else:
            resource = gen_resource.gen_group_dict(group_ids)

        host_list = [
            ServerAssets.objects.get(id=host_id).assets.asset_management_ip
            for host_id in host_ids
        ]
        selected_module_name = request.POST.get('ansibleModule')
        custom_model_name = request.POST.get('customModule')
        module_name = selected_module_name if selected_module_name != 'custom' else custom_model_name
        module_args = request.POST.get('ansibleModuleArgs')

        unique_key = '{}.{}.{}'.format(host_ids, module_name, module_args)

        if redis_conn.exists(unique_key):
            return JsonResponse({'msg': ['有相同的任务正在执行,请稍后再试'], 'code': 403})
        else:
            try:
                redis_conn.set(unique_key, 1)
                ans = ANSRunner(resource,
                                become='yes',
                                become_method='sudo',
                                become_user='******')
                ans.run_module(host_list=host_list,
                               module_name=module_name,
                               module_args=module_args)
                res = ans.get_model_result()

                return JsonResponse({'code': 200, 'msg': res})
            except Exception as e:
                return JsonResponse({
                    'code': 500,
                    'msg': ['任务执行失败:{}'.format(e)]
                })
            finally:
                redis_conn.delete(unique_key)
    inventory = AnsibleInventory.objects.prefetch_related('ans_group_hosts')
    hosts = ServerAssets.objects.select_related('assets')
    return render(request, 'task/run_module.html', locals())
예제 #7
0
파일: views.py 프로젝트: nikozhangwj/Ops
def get_top_data(request, pk):
    server_obj = ServerAssets.objects.select_related('assets').get(id=pk)
    resource = [{"ip": server_obj.assets.asset_management_ip, "port": int(server_obj.port),
                 "username": server_obj.username,
                 "password": CryptPwd().decrypt_pwd(server_obj.password)}]

    ans = ANSRunner(resource, become='yes', become_method='sudo', become_user='******')
    ans.run_module(host_list=[server_obj.assets.asset_management_ip], module_name='shell',
                   module_args='export COLUMNS\=400 && top -bcn 1 && df -h -t ext3 -t ext4 -t xfs')
    result = ans.get_module_results[0]
    if 'success' in result:
        load, tasks, cpu, mem, swap, heads, body, disk = handle_top_data(result)
        return JsonResponse({'code': 200, 'data': {'load': load, 'tasks': tasks, 'cpu': cpu, 'mem': mem, 'swap': swap,
                                                   'heads': heads, 'body': body, 'disk': disk}, 'msg': '收集成功!'})
    else:
        return JsonResponse({'code': 500, 'msg': '收集失败!{}'.format(result[result.index('>>') + 1:])})
예제 #8
0
파일: views.py 프로젝트: nikozhangwj/Ops
def server_facts(request):
    if request.method == 'POST':
        pk = request.POST.get('pk')
        module = request.POST.get('module')
        server_obj = ServerAssets.objects.select_related('assets').get(id=pk)
        resource = [{"ip": server_obj.assets.asset_management_ip, "port": int(server_obj.port),
                     "username": server_obj.username,
                     "password": CryptPwd().decrypt_pwd(server_obj.password)}]

        try:
            ans = ANSRunner(resource, become='yes', become_method='sudo', become_user='******')
            ans.run_module(host_list=[server_obj.assets.asset_management_ip], module_name=module, module_args="")

            for data in ans.get_module_results:
                if module == 'setup':
                    if 'success' in data:
                        server_info, server_model, nks = handle_setup_data(data)
                        Assets.objects.filter(id=server_obj.assets_id).update(
                            asset_model=server_model
                        )
                        ServerAssets.objects.select_related('assets').filter(id=pk).update(**server_info)

                        asset = Assets.objects.get(id=server_obj.assets_id)
                        for nk in nks:
                            mac = nk.get('network_card_mac')
                            NetworkCardAssets.objects.select_related('asset').update_or_create(defaults=nk, asset=asset,
                                                                                               network_card_mac=mac)
                        return JsonResponse({'code': 200, 'msg': '收集完成!'})
                    else:
                        return JsonResponse({'code': 500, 'msg': '收集失败!{}'.format(data[data.index('>>') + 1:])})
                elif module == 'get_mem':
                    if 'success' in data:
                        mem_infos = handle_mem_data(data)

                        asset = Assets.objects.get(id=server_obj.assets_id)
                        for mem_info in mem_infos:
                            ram_slot = mem_info.get('ram_slot')
                            RamAssets.objects.select_related('asset').update_or_create(defaults=mem_info, asset=asset,
                                                                                       ram_slot=ram_slot)
                        return JsonResponse({'code': 200, 'msg': '收集完成!'})
                    else:
                        return JsonResponse({'code': 500, 'msg': '收集失败!{}'.format(data[data.index('>>') + 1:])})
        except Exception as e:
            return JsonResponse({'code': 500, 'msg': str(e)})
예제 #9
0
파일: views.py 프로젝트: ziguicxd/Ops
def fort_server(request):
    if request.user.is_superuser:
        fort_servers = FortServer.objects.select_related('server')
        black_commands, created = FortBlackCommand.objects.get_or_create(id=1)
        fort_users = FortServerUser.objects.select_related('fort_server')
        if request.method == 'POST':
            try:
                new_black_commands = request.POST.get('black_commands')

                if fort_users.count() > 0:

                    old_format_commands = format_commands(
                        black_commands.black_commands)
                    new_format_commands = format_commands(new_black_commands)

                    for fort_server_obj in fort_servers:
                        sudo_users = [
                            user.fort_username for user in
                            fort_server_obj.fortserveruser_set.all()
                        ]

                        resource = gen_resource(
                            list(str(fort_server_obj.server.id)))
                        ans = ANSRunner(resource)
                        ans.run_module(
                            host_list=fort_server_obj.server.assets.
                            asset_management_ip,
                            module_name='shell',
                            module_args=
                            r"cd /etc/sudoers.d/ && sed -i 's@{}@{}@' {}".
                            format(old_format_commands, new_format_commands,
                                   ' '.join(sudo_users)))
                        res = ans.get_model_result()[0]
                        if 'success' in res:
                            FortBlackCommand.objects.filter(id=1).update(
                                black_commands=new_black_commands)
                            return JsonResponse({'code': 200, 'msg': '更新成功!'})
                        else:
                            return JsonResponse({
                                'code':
                                500,
                                'msg':
                                '{}ansible更新失败!:{}'.format(
                                    fort_server_obj.server.assets.
                                    asset_management_ip, res)
                            })
                else:
                    FortBlackCommand.objects.filter(id=1).update(
                        black_commands=new_black_commands)
                    return JsonResponse({'code': 200, 'msg': '更新成功!'})
            except Exception as e:
                return JsonResponse({'code': 500, 'msg': '更新失败!:{}'.format(e)})

        hosts = ServerAssets.objects.select_related('assets')
        server_status = FortServer.server_status_
        fort_user_status = FortServerUser.fort_user_status_
        users = UserProfile.objects.all()
        groups = Group.objects.all()
        return render(request, 'fort/fort_server.html', locals())
    else:
        return HttpResponseForbidden('<h1>403</h1>')