Esempio n. 1
0
def download(request):
    user = request.user
    assets = get_group_user_perm(user).get('asset').keys()
    asset_select = []
    if request.method == 'POST':
        remote_ip = request.META.get('REMOTE_ADDR')
        asset_ids = request.POST.getlist('asset_ids', '')
        file_path = request.POST.get('file_path')
        date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        upload_dir = get_tmp_dir()
        for asset_id in asset_ids:
            asset_select.append(get_object(Asset, id=asset_id))

        if not set(asset_select).issubset(set(assets)):
            illegal_asset = set(asset_select).issubset(set(assets))
            return HttpResponse(u'没有权限的服务器 %s' % ','.join([asset.name for asset in illegal_asset]))

        res = gen_resource({'user': user, 'asset': asset_select})
        runner = MyRunner(res)
        runner.run('fetch', module_args='src=%s dest=%s' % (file_path, upload_dir), pattern='*')
        FileLog(user=request.user.username, host=' '.join([asset.name for asset in asset_select]),
                filename=file_path, type='download', remote_ip=remote_ip, result=runner.results).save()
        logger.debug(runner.results)
        os.chdir('/tmp')
        tmp_dir_name = os.path.basename(upload_dir)
        tar_file = '%s.tar.gz' % upload_dir
        bash('tar czf %s %s' % (tar_file, tmp_dir_name))
        f = open(tar_file)
        data = f.read()
        f.close()
        response = HttpResponse(data, content_type='application/octet-stream')
        response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(tar_file)
        return response

    return render_to_response('download.html', locals(), context_instance=RequestContext(request))
Esempio n. 2
0
def update_asset_info(need_update_asset, name, proxy=None):
    """
    更新资产信息
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        update_proxy_asset = list(set(proxy_asset) & set(need_update_asset))
        host_list = [
            asset.networking.all()[0].ip_address
            for asset in update_proxy_asset
        ]
        if host_list:
            resource = gen_resource(update_proxy_asset)
            data = {
                'mod_name': 'setup',
                'resource': resource,
                'hosts': host_list,
                'mod_args': '',
                'run_action': 'sync',
                'run_type': 'ad-hoc'
            }
            data = json.dumps(data)
            api = APIRequest('{0}/v1.0/module'.format(proxy.url),
                             proxy.username, CRYPTOR.decrypt(proxy.password))
            result, code = api.req_post(data)
            logger.debug(u'更新操作结果result:%s       code:%s' % (result, code))
            if code == 200 and result['messege']['success']:
                asset_ansible_update(update_proxy_asset, result, name)
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
Esempio n. 3
0
def update_asset_info(need_update_asset, name, proxy=None):
    """
    更新资产信息
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        update_proxy_asset = list(set(proxy_asset) & set(need_update_asset))
        host_list = [asset.networking.all()[0].ip_address for asset in update_proxy_asset]
        if host_list:
            resource = gen_resource(update_proxy_asset)
            data = {'mod_name': 'setup',
                    'resource': resource,
                    'hosts': host_list,
                    'mod_args': '',
                    'run_action': 'sync',
                    'run_type': 'ad-hoc'
                    }
            data = json.dumps(data)
            api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
            result, code = api.req_post(data)
            logger.debug(u'更新操作结果result:%s       code:%s' % (result,code))
            if code == 200 and result['messege']['success']:
                asset_ansible_update(update_proxy_asset, result, name)
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
Esempio n. 4
0
    def download(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "进入批量下载模式"
                print "请输入主机名或ansible支持的pattern, 多个主机:分隔,q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == 'q':
                    break
                else:
                    assets = self.user_perm.get('asset').keys()
                    res = gen_resource({'user': self.user, 'asset': assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ''
                    print "匹配主机:\n"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        asset_name_str += '%s ' % inv.name
                        print ' %s' % inv.name
                    if not asset_name_str:
                        color_print('没有匹配主机')
                        continue
                    print
                    while True:
                        tmp_dir = get_tmp_dir()
                        logger.debug('Download tmp dir: %s' % tmp_dir)
                        print "请输入文件路径(不支持目录)"
                        file_path = raw_input("\033[1;32mPath>:\033[0m ").strip()
                        if file_path == 'q':
                            break

                        if not file_path:
                            color_print("文件路径为空")
                            continue

                        runner.run('fetch', module_args='src=%s dest=%s' % (file_path, tmp_dir), pattern=pattern)
                        ret = runner.results
                        FileLog(user=self.user.name, host=asset_name_str, filename=file_path, type='download',
                                remote_ip=remote_ip, result=ret).save()
                        logger.debug('Download file result: %s' % ret)
                        os.chdir('/tmp')
                        tmp_dir_name = os.path.basename(tmp_dir)
                        if not os.listdir(tmp_dir):
                            color_print('下载全部失败')
                            continue
                        bash('tar czf %s.tar.gz %s && sz %s.tar.gz' % (tmp_dir, tmp_dir_name, tmp_dir))

                        if ret.get('failed'):
                            error = '文件名称: %s \n下载失败: [ %s ] \n下载成功 [ %s ]' % \
                                    ('%s.tar.gz' % tmp_dir_name, ', '.join(ret.get('failed').keys()), ', '.join(ret.get('ok').keys()))
                            color_print(error)
                        else:
                            msg = '文件名称: %s \n下载成功 [ %s ]' % ('%s.tar.gz' % tmp_dir_name, ', '.join(ret.get('ok').keys()))
                            color_print(msg, 'green')
                        print
            except IndexError:
                pass
Esempio n. 5
0
def execute_commands(request):
    proxy_id = request.GET.get('id')
    try:
        proxy = Proxy.objects.get(id=int(proxy_id))
        proxy_assets = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        resource = gen_resource(proxy_assets)
        return my_render('proxyManage/exec_commands.html', locals(), request)
    except Exception as e:
        logger.error(e)
        return HttpResponse(e)
Esempio n. 6
0
def execute_commands(request):
    proxy_id = request.GET.get('id')
    try:
        proxy = Proxy.objects.get(id=int(proxy_id))
        proxy_assets = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        resource = gen_resource(proxy_assets)
        return my_render('proxyManage/exec_commands.html', locals(), request)
    except Exception as e:
        logger.error(e)
        return HttpResponse(e)
Esempio n. 7
0
    def upload(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "进入批量上传模式"
                print "请输入主机名或ansible支持的pattern, 多个主机:分隔 q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == 'q':
                    break
                else:
                    assets = self.user_perm.get('asset').keys()
                    res = gen_resource({'user': self.user, 'asset': assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ''
                    print "匹配主机:"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        print inv.name
                        asset_name_str += '%s ' % inv.name

                    if not asset_name_str:
                        color_print('没有匹配主机')
                        continue
                    tmp_dir = get_tmp_dir()
                    logger.debug('Upload tmp dir: %s' % tmp_dir)
                    os.chdir(tmp_dir)
                    bash('rz')
                    filename_str = ' '.join(os.listdir(tmp_dir))
                    if not filename_str:
                        color_print("上传文件为空")
                        continue
                    logger.debug('上传文件: %s' % filename_str)

                    runner = MyRunner(res)
                    runner.run('copy', module_args='src=%s dest=%s directory_mode'
                                                     % (tmp_dir, '/tmp'), pattern=pattern)
                    ret = runner.results
                    FileLog(user=self.user.name, host=asset_name_str, filename=filename_str,
                            remote_ip=remote_ip, type='upload', result=ret).save()
                    logger.debug('Upload file: %s' % ret)
                    if ret.get('failed'):
                        error = '上传目录: %s \n上传失败: [ %s ] \n上传成功 [ %s ]' % (tmp_dir,
                                                                             ', '.join(ret.get('failed').keys()),
                                                                             ', '.join(ret.get('ok').keys()))
                        color_print(error)
                    else:
                        msg = '上传目录: %s \n传送成功 [ %s ]' % (tmp_dir, ', '.join(ret.get('ok').keys()))
                        color_print(msg, 'green')
                    print

            except IndexError:
                pass
Esempio n. 8
0
def perm_role_recycle(request):
    role_id = request.GET.get('role_id')
    asset_ids = request.GET.get('asset_id').split(',')

    # 仅有推送的角色才回收
    assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids]
    recycle_assets = []
    for asset in assets:
        if True in [push.success for push in asset.perm_push.all()]:
            recycle_assets.append(asset)
    recycle_resource = gen_resource(recycle_assets)
    task = MyTask(recycle_resource)
    try:
        msg_del_user = task.del_user(get_object(PermRole, id=role_id).name)
        msg_del_sudo = task.del_user_sudo(get_object(PermRole, id=role_id).name)
        logger.info("recycle user msg: %s" % msg_del_user)
        logger.info("recycle sudo msg: %s" % msg_del_sudo)
    except Exception, e:
        logger.warning("Recycle Role failed: %s" % e)
        raise ServerError(u"回收已推送的系统用户失败: %s" % e)
Esempio n. 9
0
def perm_role_recycle(request):
    role_id = request.GET.get('role_id')
    asset_ids = request.GET.get('asset_id').split(',')

    # 仅有推送的角色才回收
    assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids]
    recycle_assets = []
    for asset in assets:
        if True in [push.success for push in asset.perm_push.all()]:
            recycle_assets.append(asset)
    recycle_resource = gen_resource(recycle_assets)
    task = MyTask(recycle_resource)
    try:
        msg_del_user = task.del_user(get_object(PermRole, id=role_id).name)
        msg_del_sudo = task.del_user_sudo(
            get_object(PermRole, id=role_id).name)
        logger.info("recycle user msg: %s" % msg_del_user)
        logger.info("recycle sudo msg: %s" % msg_del_sudo)
    except Exception, e:
        logger.warning("Recycle Role failed: %s" % e)
        raise ServerError(u"回收已推送的系统用户失败: %s" % e)
Esempio n. 10
0
def upload(request):
    user = request.user
    assets = get_group_user_perm(user).get('asset').keys()
    asset_select = []
    if request.method == 'POST':
        remote_ip = request.META.get('REMOTE_ADDR')
        asset_ids = request.POST.getlist('asset_ids', '')
        upload_files = request.FILES.getlist('file[]', None)
        date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        upload_dir = get_tmp_dir()
        for asset_id in asset_ids:
            asset_select.append(get_object(Asset, id=asset_id))

        if not set(asset_select).issubset(set(assets)):
            illegal_asset = set(asset_select).issubset(set(assets))
            return HttpResponse('没有权限的服务器 %s' % ','.join([asset.name for asset in illegal_asset]))

        for upload_file in upload_files:
            file_path = '%s/%s' % (upload_dir, upload_file.name)
            with open(file_path, 'w') as f:
                for chunk in upload_file.chunks():
                    f.write(chunk)

        res = gen_resource({'user': user, 'asset': asset_select})
        runner = MyRunner(res)
        runner.run('copy', module_args='src=%s dest=%s directory_mode'
                                        % (upload_dir, '/tmp'), pattern='*')
        ret = runner.results
        logger.debug(ret)
        FileLog(user=request.user.username, host=' '.join([asset.name for asset in asset_select]),
                filename=' '.join([f.name for f in upload_files]), type='upload', remote_ip=remote_ip,
                result=ret).save()
        if ret.get('failed'):
            error = u'上传目录: %s <br> 上传失败: [ %s ] <br>上传成功 [ %s ]' % (upload_dir,
                                                                                ','.join(ret.get('failed').keys()),
                                                                                ','.join(ret.get('ok').keys()))
            return HttpResponse(error, status=500)
        msg = u'上传目录: %s <br> 传送成功 [ %s ]' % (upload_dir, ', '.join(ret.get('ok').keys()))
        return HttpResponse(msg)
    return my_render('upload.html', locals(), request)
Esempio n. 11
0
try:
    role_id = request.POST.get("id")
    role = get_object(PermRole, id=int(role_id))
    if not role:
        logger.warning(u"Delete Role: role_id %s not exist" % role_id)
        raise ServerError(u"role_id %s 无数据记录" % role_id)
    recycle_assets = [
        push.asset for push in role.perm_push.all() if push.success
    ]
    logger.debug(u"delete role %s - delete_assets: %s" %
                 (role.name, recycle_assets))
    if recycle_assets:
        asset_proxys = gen_asset_proxy(recycle_assets)
        for key, value in asset_proxys.items():
            proxy = Proxy.objects.filter(proxy_name=key)[0]
            recycle_resource = gen_resource(value)
            host_list = [
                asset.networking.all()[0].ip_address for asset in value
            ]
            task = MyTask(recycle_resource, host_list)
            try:
                msg_del_user = task.del_user(role.name, proxy,
                                             request.user.username)
                msg_del_sudo = task.del_user_sudo(
                    role.uuid_id, proxy, request.user.username)
            except Exception, e:
                logger.warning(u"Recycle Role failed: %s" % e)
                raise ServerError(u"回收已推送的系统用户失败: %s" % e)
            logger.info(u"删除用户 %s - execute delete user: %s" %
                        (role.name, msg_del_user))
            logger.info(u"删除用户 %s - execute delete sudo: %s" %
Esempio n. 12
0
    def exec_cmd(self):
        """
        批量执行命令
        """
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)

            roles = self.user_perm.get('role').keys()
            if len(roles) > 1:  # 授权角色数大于1
                color_print('[%-2s] %-15s' % ('ID', '系统用户'),  'info')
                role_check = dict(zip(range(len(roles)), roles))

                for i, r in role_check.items():
                    print '[%-2s] %-15s' % (i, r.name)
                print
                print "请输入运行命令所关联系统用户的ID, q退出"

                try:
                    role_id = raw_input("\033[1;32mRole>:\033[0m ").strip()
                    if role_id == 'q':
                        break
                except (IndexError, ValueError):
                    color_print('错误输入')
                else:
                    role = role_check[int(role_id)]
            elif len(roles) == 1:  # 授权角色数为1
                role = roles[0]
            else:
                color_print('当前用户未被授予角色,无法执行任何操作,如有疑问请联系管理员。')
                return
            assets = list(self.user_perm.get('role', {}).get(role).get('asset'))  # 获取该用户,角色授权主机
            print "授权包含该系统用户的所有主机"
            for asset in assets:
                print ' %s' % asset.name
            print
            print "请输入主机名或ansible支持的pattern, 多个主机:分隔, q退出"
            pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
            if pattern == 'q':
                break
            else:
                res = gen_resource({'user': self.user, 'asset': assets, 'role': role}, perm=self.user_perm)
                runner = MyRunner(res)
                asset_name_str = ''
                print "匹配主机:"
                for inv in runner.inventory.get_hosts(pattern=pattern):
                    print ' %s' % inv.name
                    asset_name_str += '%s ' % inv.name
                print

                while True:
                    print "请输入执行的命令, 按q退出"
                    command = raw_input("\033[1;32mCmds>:\033[0m ").strip()
                    if command == 'q':
                        break
                    elif not command:
                        color_print('命令不能为空...')
                        continue
                    runner.run('shell', command, pattern=pattern)
                    ExecLog(host=asset_name_str, user=self.user.username, cmd=command, remote_ip=remote_ip,
                            result=runner.results).save()
                    for k, v in runner.results.items():
                        if k == 'ok':
                            for host, output in v.items():
                                color_print("%s => %s" % (host, 'Ok'), 'green')
                                print output
                                print
                        else:
                            for host, output in v.items():
                                color_print("%s => %s" % (host, k), 'red')
                                color_print(output, 'red')
                                print
                    print "~o~ Task finished ~o~"
                    print
Esempio n. 13
0
        except ServerError, e:
            return HttpResponse(e)
    if request.method == "POST":
        try:
            role_id = request.POST.get("id")
            role = get_object(PermRole, id=int(role_id))
            if not role:
                logger.warning(u"Delete Role: role_id %s not exist" % role_id)
                raise ServerError(u"role_id %s 无数据记录" % role_id)
            recycle_assets = [push.asset for push in role.perm_push.all() if push.success]
            logger.debug(u"delete role %s - delete_assets: %s" % (role.name, recycle_assets))
            if recycle_assets:
                asset_proxys = gen_asset_proxy(recycle_assets)
                for key, value in asset_proxys.items():
                    proxy = Proxy.objects.filter(proxy_name=key)[0]
                    recycle_resource = gen_resource(value)
                    host_list = [asset.networking.all()[0].ip_address for asset in value]
                    task = MyTask(recycle_resource, host_list)
                    try:
                        msg_del_user = task.del_user(role.name, proxy, request.user.username)
                        msg_del_sudo = task.del_user_sudo(role.uuid_id, proxy, request.user.username)
                    except Exception, e:
                        logger.warning(u"Recycle Role failed: %s" % e)
                        raise ServerError(u"回收已推送的系统用户失败: %s" % e)
                    logger.info(u"删除用户 %s - execute delete user: %s" % (role.name, msg_del_user))
                    logger.info(u"删除用户 %s - execute delete sudo: %s" % (role.name, msg_del_sudo))
                    # TODO: 判断返回结果,处理异常

            # 删除proxy上的role, proxy上的role删除成功后再删除magicstack上的role
            proxy_list = Proxy.objects.all()
            data = {