コード例 #1
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())
コード例 #2
0
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 = 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)))
                        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>')
コード例 #3
0
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)
            ans.run_module(host_list=[server_obj.assets.asset_management_ip],
                           module_name=module,
                           module_args="")
            res = ans.get_model_result()
            for data in res:
                if module == 'setup':
                    if 'success' in data:
                        server_info, server_model, nks = ans.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 = ans.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)})