コード例 #1
0
def user_perm_asset_num(user_id):
    user = get_object(User, id=user_id)
    if user:
        user_perm_info = get_group_user_perm(user)
        return len(list(user_perm_info.get('asset').keys()))
    else:
        return 0
コード例 #2
0
ファイル: connect.py プロジェクト: 3mao/jumpserver
 def __init__(self, user):
     self.user = user
     self.user_perm = get_group_user_perm(self.user)
     self.perm_assets = sorted(self.user_perm.get('asset', []).keys(),
                               key=lambda x: [int(num) for num in x.ip.split('.') if num.isdigit()])
     self.search_result = self.perm_assets
     self.perm_asset_groups = self.user_perm.get('asset_group', [])
コード例 #3
0
 def __init__(self, user):
     self.user = user
     self.search_result = None
     self.user_perm = get_group_user_perm(self.user)
     self.perm_assets = sorted(self.user_perm.get('asset', []).keys(),
                               key=lambda x: [int(num) for num in x.ip.split('.') if num.isdigit()])
     self.perm_asset_groups = self.user_perm.get('asset_group', [])
コード例 #4
0
ファイル: content.py プロジェクト: vanwt/ttcmdb
    def search(self, str_r=''):
        gid_pattern = re.compile(r'^g\d+$')
        # 获取用户授权的所有主机信息
        if not self.user_perm:
            self.user_perm = get_group_user_perm(self.user)
        user_asset_all = self.user_perm.get('asset').keys()
        # 搜索结果保存
        user_asset_search = []
        if str_r:
            # 资产组组id匹配
            if gid_pattern.match(str_r):
                gid = int(str_r.lstrip('g'))
                # 获取资产组包含的资产
                user_asset_search = get_object(AssetGroup, id=gid).asset_set.all()
            else:
                # 匹配 ip, hostname, 备注
                for asset in user_asset_all:
                    if str_r in asset.ip or str_r in str(asset.hostname) or str_r in str(asset.comment):
                        user_asset_search.append(asset)
        else:
            # 如果没有输入就展现所有
            user_asset_search = user_asset_all

        self.search_result = dict(zip(range(len(user_asset_search)), user_asset_search))
        color_print('[%-3s] %-12s %-15s  %-5s  %-10s  %s' % ('ID', u'主机名', 'IP', u'端口', u'系统用户', u'备注'), 'title')
        for index, asset in self.search_result.items():
            # 获取该资产信息
            asset_info = get_asset_info(asset)
            # 获取该资产包含的角色
            role = [str(role.name) for role in self.user_perm.get('asset').get(asset).get('role')]
            print
            '[%-3s] %-15s %-15s  %-5s  %-10s  %s' % (index, asset.hostname, asset.ip, asset_info.get('port'),
                                                     role, asset.comment)
        print
コード例 #5
0
ファイル: connect.py プロジェクト: 277800076/jumpserver
    def search(self, str_r=''):
        gid_pattern = re.compile(r'^g\d+$')
        # 获取用户授权的所有主机信息
        if not self.user_perm:
            self.user_perm = get_group_user_perm(self.user)
        user_asset_all = self.user_perm.get('asset').keys()
        # 搜索结果保存
        user_asset_search = []
        if str_r:
            # 资产组组id匹配
            if gid_pattern.match(str_r):
                gid = int(str_r.lstrip('g'))
                # 获取资产组包含的资产
                user_asset_search = get_object(AssetGroup, id=gid).asset_set.all()
            else:
                # 匹配 ip, hostname, 备注
                for asset in user_asset_all:
                    if str_r in asset.ip or str_r in str(asset.hostname) or str_r in str(asset.comment):
                        user_asset_search.append(asset)
        else:
            # 如果没有输入就展现所有
            user_asset_search = user_asset_all

        self.search_result = dict(zip(range(len(user_asset_search)), user_asset_search))
        color_print('[%-3s] %-12s %-15s  %-5s  %-10s  %s' % ('ID', '主机名', 'IP', '端口', '系统用户', '备注'), 'title')
        for index, asset in self.search_result.items():
            # 获取该资产信息
            asset_info = get_asset_info(asset)
            # 获取该资产包含的角色
            role = [str(role.name) for role in self.user_perm.get('asset').get(asset).get('role')]
            print '[%-3s] %-15s %-15s  %-5s  %-10s  %s' % (index, asset.hostname, asset.ip, asset_info.get('port'),
                                                            role, asset.comment)
        print
コード例 #6
0
ファイル: mytags.py プロジェクト: coderlz/jumpserver
def get_perm_asset_num(user_id):
    user = get_object(User, id=user_id)
    if user:
        user_perm_info = get_group_user_perm(user)
        return len(user_perm_info['asset'].keys())
    else:
        return 0
コード例 #7
0
ファイル: views.py プロジェクト: Felix-YuJing/jumpserver
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.hostname 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.hostname 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))
コード例 #8
0
ファイル: mytags.py プロジェクト: ljb-2000/jumpserver-1
def user_perm_asset_num(user_id):
    user = get_object(User, id=user_id)
    if user:
        user_perm_info = get_group_user_perm(user)
        return len(user_perm_info.get('asset').keys())
    else:
        return 0
コード例 #9
0
ファイル: connect.py プロジェクト: Aroundight/jump-jump
 def __init__(self, user):
     self.user = user
     self.user_perm = get_group_user_perm(self.user)
     self.perm_assets = sorted(self.user_perm.get('asset', []))
     self.search_result = self.perm_assets
     self.perm_asset_groups = self.user_perm.get('asset_group', [])
     logger.info("get group is: %s", self.perm_asset_groups)
コード例 #10
0
ファイル: content.py プロジェクト: vanwt/ttcmdb
    def download(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print("进入批量下载模式")
                print("请输入主机名或ansile支持的pattern, 多个主机:分隔,q退出")
                pattern = 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 = 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
コード例 #11
0
ファイル: connect.py プロジェクト: love4j/jumpserver
 def print_asset_group(self):
     """
     打印用户授权的资产组
     """
     user_asset_group_all = get_group_user_perm(self.user).get('asset_group', [])
     color_print('[%-3s] %-20s %s' % ('ID', '组名', '备注'), 'title')
     for asset_group in user_asset_group_all:
         print '[%-3s] %-15s %s' % (asset_group.id, asset_group.name, asset_group.comment)
     print
コード例 #12
0
ファイル: connect.py プロジェクト: 277800076/jumpserver
    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
コード例 #13
0
ファイル: connect.py プロジェクト: cn27001/jumpserver
 def print_asset_group(self):
     """
     打印用户授权的资产组
     """
     user_asset_group_all = get_group_user_perm(self.user).get("asset_group", [])
     color_print("[%-3s] %-20s %s" % ("ID", "组名", "备注"), "title")
     for asset_group in user_asset_group_all:
         print "[%-3s] %-15s %s" % (asset_group.id, asset_group.name, asset_group.comment)
     print
コード例 #14
0
ファイル: connect.py プロジェクト: 280455936/jumpserver
 def print_asset_group(self):
     """
     打印用户授权的资产组
     """
     user_asset_group_all = get_group_user_perm(self.user).get('asset_group', [])
     color_print('[%-3s] %-20s %s' % ('ID', '组名', '备注'), 'title')
     for asset_group in user_asset_group_all:
         print '[%-3s] %-15s %s' % (asset_group.id, asset_group.name, asset_group.comment)
     print
コード例 #15
0
def download(request):
    user = request.user
    assets = list(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")
        download_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.hostname 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, download_dir),
                   pattern='*')
        FileLog(user=request.user.username,
                host=' '.join([asset.hostname for asset in asset_select]),
                filename=file_path,
                type='download',
                remote_ip=remote_ip,
                result=runner.results).save()
        logger.debug(runner.results)
        tmp_dir_name = os.path.basename(download_dir)
        file_zip = '/tmp/' + tmp_dir_name + '.zip'
        zf = zipfile.ZipFile(file_zip, "w", zipfile.ZIP_DEFLATED)

        for dirname, subdirs, files in os.walk(download_dir):
            arcname = dirname.split(download_dir)[-1]
            if arcname:
                zf.write(dirname, arcname)
            for filename in files:
                filename = os.path.join(dirname, filename)
                arcname = filename.split(download_dir)[-1]
                zf.write(filename, arcname)

        zf.close()
        f = open(file_zip, 'rb')
        data = f.read()
        f.close()
        response = HttpResponse(data, content_type='application/octet-stream')
        response[
            'Content-Disposition'] = 'attachment; filename=%s.zip' % tmp_dir_name
        return response

    return render(request, 'download.html', locals())
コード例 #16
0
ファイル: connect.py プロジェクト: zweipeng/AwesomeDockerfile
 def __init__(self, user):
     self.user = user
     self.user_perm = get_group_user_perm(self.user)
     if NAV_SORT_BY == 'ip':
         self.perm_assets = sorted(self.user_perm.get('asset', []).keys(),
                                   key=lambda x: [int(num) for num in x.ip.split('.') if num.isdigit()])
     elif NAV_SORT_BY == 'hostname':
         self.perm_assets = self.natural_sort_hostname(self.user_perm.get('asset', []).keys())
     else:
         self.perm_assets = tuple(self.user_perm.get('asset', []))
     self.search_result = self.perm_assets
     self.perm_asset_groups = self.user_perm.get('asset_group', [])
コード例 #17
0
ファイル: connect.py プロジェクト: 280455936/jumpserver
 def __init__(self, user):
     self.user = user
     self.user_perm = get_group_user_perm(self.user)
     if NAV_SORT_BY == 'ip':
         self.perm_assets = sorted(self.user_perm.get('asset', []).keys(),
                                   key=lambda x: [int(num) for num in x.ip.split('.') if num.isdigit()])
     elif NAV_SORT_BY == 'hostname':
         self.perm_assets = self.natural_sort_hostname(self.user_perm.get('asset', []).keys())
     else:
         self.perm_assets = tuple(self.user_perm.get('asset', []))
     self.search_result = self.perm_assets
     self.perm_asset_groups = self.user_perm.get('asset_group', [])
コード例 #18
0
ファイル: connect.py プロジェクト: 277800076/jumpserver
    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_dir), 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
コード例 #19
0
ファイル: content.py プロジェクト: vanwt/ttcmdb
    def upload(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print("进入批量上传模式")
                print("请输入主机名或ansile支持的pattern, 多个主机:分隔 q退出")
                pattern = 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_dir), 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
コード例 #20
0
ファイル: asset_api.py プロジェクト: a-robot/jumpserver_old
def get_assets_by_username(username):
    """
    get assets those the user has permission to
    """
    asset_id_all = []
    user = get_object(User, username=username)
    asset_perm = get_group_user_perm(user) if user else {'asset': ''}
    user_asset_perm = list(asset_perm['asset'].keys())
    for asset in user_asset_perm:
        asset_id_all.append(asset.id)

    asset_find = Asset.objects.filter(pk__in=asset_id_all)
    return asset_find
コード例 #21
0
ファイル: views.py プロジェクト: peterpijing/Jumpserverself
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()
        # file_dict = {}
        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.hostname 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)

        #TODO 更改文件上传路径
        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.hostname 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)
コード例 #22
0
def perm_role_get(request):
    asset_id = request.GET.get('id', 0)
    if asset_id:
        asset = get_object(Asset, id=asset_id)
        if asset:
            role = user_have_perm(request.user, asset=asset)
            username_list = [i.name for i in role]
            logger.debug('获取授权系统用户: ' + ','.join(username_list))
            return HttpResponse(','.join([i.name for i in role]))
    else:
        roles = list(get_group_user_perm(request.user).get('role').keys())
        username_list = [i.name for i in roles]
        return HttpResponse(','.join(username_list))

    return HttpResponse('error')
コード例 #23
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.hostname 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.hostname 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))
コード例 #24
0
ファイル: views.py プロジェクト: xiaochao/bounce
def user_detail(request):
    header_title, path1, path2 = "用户详情", "用户管理", "用户详情"
    if request.session.get("role_id") == 0:
        user_id = request.user.id
    else:
        user_id = request.GET.get("id", "")

    user = get_object(User, id=user_id)
    if not user:
        return HttpResponseRedirect(reverse("user_list"))

    user_perm_info = get_group_user_perm(user)
    role_assets = user_perm_info.get("role")
    user_log_ten = Log.objects.filter(user=user.username).order_by("id")[0:10]
    user_log_last = Log.objects.filter(user=user.username).order_by("id")[0:50]
    user_log_last_num = len(user_log_last)

    return my_render("juser/user_detail.html", locals(), request)
コード例 #25
0
ファイル: views.py プロジェクト: Felix-YuJing/jumpserver
def user_detail(request):
    header_title, path1, path2 = '用户详情', '用户管理', '用户详情'
    if request.session.get('role_id') == 0:
        user_id = request.user.id
    else:
        user_id = request.GET.get('id', '')

    user = get_object(User, id=user_id)
    if not user:
        return HttpResponseRedirect(reverse('user_list'))

    user_perm_info = get_group_user_perm(user)
    role_assets = user_perm_info.get('role')
    user_log_ten = Log.objects.filter(user=user.username).order_by('id')[0:10]
    user_log_last = Log.objects.filter(user=user.username).order_by('id')[0:50]
    user_log_last_num = len(user_log_last)

    return my_render('juser/user_detail.html', locals(), request)
コード例 #26
0
def user_detail(request):
    header_title, path1, path2 = '用户详情', '用户管理', '用户详情'
    if request.session.get('role_id') == 0:
        user_id = request.user.id
    else:
        user_id = request.GET.get('id', '')

    user = get_object(User, id=user_id)
    if not user:
        return HttpResponseRedirect(reverse('user_list'))

    user_perm_info = get_group_user_perm(user)
    role_assets = user_perm_info.get('role')
    user_log_ten = Log.objects.filter(user=user.username).order_by('id')[0:10]
    user_log_last = Log.objects.filter(user=user.username).order_by('id')[0:50]
    user_log_last_num = len(user_log_last)

    return my_render('juser/user_detail.html', locals(), request)
コード例 #27
0
ファイル: views.py プロジェクト: Felix-YuJing/jumpserver
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()
        # file_dict = {}
        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.hostname 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, upload_dir), pattern='*')
        ret = runner.results
        logger.debug(ret)
        FileLog(user=request.user.username, host=' '.join([asset.hostname 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)
コード例 #28
0
ファイル: connect.py プロジェクト: cn27001/jumpserver
    def search(self, str_r=""):
        gid_pattern = re.compile(r"^g\d+$")
        # 获取用户授权的所有主机信息
        if not self.user_perm:
            self.user_perm = get_group_user_perm(self.user)
        user_asset_all = self.user_perm.get("asset").keys()
        # 搜索结果保存
        user_asset_search = []
        if str_r:
            # 资产组组id匹配
            if gid_pattern.match(str_r):
                gid = int(str_r.lstrip("g"))
                # 获取资产组包含的资产
                user_asset_search = get_object(AssetGroup, id=gid).asset_set.all()
            else:
                # 匹配 ip, hostname, 备注
                for asset in user_asset_all:
                    if str_r in asset.ip or str_r in str(asset.hostname) or str_r in str(asset.comment):
                        user_asset_search.append(asset)
        else:
            # 如果没有输入就展现所有
            user_asset_search = user_asset_all

        self.search_result = dict(zip(range(len(user_asset_search)), user_asset_search))
        color_print("[%-3s] %-12s %-15s  %-5s  %-10s  %s" % ("ID", "主机名", "IP", "端口", "系统用户", "备注"), "title")
        for index, asset in self.search_result.items():
            # 获取该资产信息
            asset_info = get_asset_info(asset)
            # 获取该资产包含的角色
            role = [str(role.name) for role in self.user_perm.get("asset").get(asset).get("role")]
            print "[%-3s] %-15s %-15s  %-5s  %-10s  %s" % (
                index,
                asset.hostname,
                asset.ip,
                asset_info.get("port"),
                role,
                asset.comment,
            )
        print
コード例 #29
0
def asset_list(request):
    """
    asset list view
    """
    header_title, path1, path2 = u'查看资产', u'资产管理', u'查看资产'
    username = request.user.username
    user_perm = request.session['role_id']
    idc_all = IDC.objects.filter()
    asset_group_all = AssetGroup.objects.all()
    asset_types = ASSET_TYPE
    asset_status = ASSET_STATUS
    idc_name = request.GET.get('idc', '')
    group_name = request.GET.get('group', '')
    asset_type = request.GET.get('asset_type', '')
    status = request.GET.get('status', '')
    keyword = request.GET.get('keyword', '')
    export = request.GET.get("export", False)
    group_id = request.GET.get("group_id", '')
    idc_id = request.GET.get("idc_id", '')
    asset_id_all = request.GET.getlist("id", '')

    if group_id:
        group = get_object(AssetGroup, id=group_id)
        if group:
            asset_find = Asset.objects.filter(group=group)
    elif idc_id:
        idc = get_object(IDC, id=idc_id)
        if idc:
            asset_find = Asset.objects.filter(idc=idc)
    else:
        if user_perm != 0:
            asset_find = Asset.objects.all()
        else:
            asset_id_all = []
            user = get_object(User, username=username)
            asset_perm = get_group_user_perm(user) if user else {'asset': ''}
            user_asset_perm = asset_perm['asset'].keys()
            for asset in user_asset_perm:
                asset_id_all.append(asset.id)
            asset_find = Asset.objects.filter(pk__in=asset_id_all)
            asset_group_all = list(asset_perm['asset_group'])

    if idc_name:
        if idc_name == 'none':
            asset_find = asset_find.filter(idc=None)
        else:
            asset_find = asset_find.filter(idc__name__contains=idc_name)

    if group_name:
        if group_name == 'none':
            asset_find = asset_find.filter(group=None)
        else:
            asset_find = asset_find.filter(group__name__contains=group_name)

    if asset_type:
        asset_find = asset_find.filter(asset_type__contains=asset_type)

    if status:
        asset_find = asset_find.filter(status__contains=status)

    if keyword:
        asset_find = asset_find.filter(
            Q(hostname__contains=keyword) | Q(other_ip__contains=keyword)
            | Q(ip__contains=keyword) | Q(remote_ip__contains=keyword)
            | Q(comment__contains=keyword) | Q(username__contains=keyword)
            | Q(group__name__contains=keyword) | Q(cpu__contains=keyword)
            | Q(memory__contains=keyword) | Q(disk__contains=keyword)
            | Q(brand__contains=keyword) | Q(cabinet__contains=keyword)
            | Q(sn__contains=keyword) | Q(system_type__contains=keyword)
            | Q(system_version__contains=keyword))

    if export:
        import traceback
        try:
            if asset_id_all:
                asset_find = []
                for asset_id in asset_id_all:
                    asset = get_object(Asset, id=asset_id)
                    if asset:
                        asset_find.append(asset)
            asset_find = asset_find.distinct()
            asset_find = sorted(
                asset_find,
                key=lambda ip: long(
                    ''.join(["%02X" % long(i) for i in ip.ip.split('.')]), 16))
            s = write_excel(asset_find)
            if s[0]:
                file_name = s[1]
            smg = u'excel文件已生成,请点击下载!'
            return my_render('jasset/asset_excel_download.html', locals(),
                             request)
        except:
            traceback.print_exc()
    # 去重,按ip排序
    asset_find = asset_find.distinct()
    asset_find = sorted(
        asset_find,
        key=lambda ip: long(
            ''.join(["%02X" % long(i) for i in ip.ip.split('.')]), 16))

    # ip排序
    if 'ip' in request.GET:
        ip = request.GET.get('ip')
        if ip == '0':
            asset_find.reverse()
    else:
        ip = '1'

    assets_list, p, assets, page_range, current_page, show_first, show_end = pages(
        asset_find, request)

    contact_list = assets_list
    contacts = assets

    if user_perm != 0:
        return my_render('jasset/asset_list.html', locals(), request)
    else:
        return my_render('jasset/asset_cu_list.html', locals(), request)
コード例 #30
0
    def exec_cmd(self):
        """
        批量执行命令
        """
        while True:
            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 = int(
                        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

#判断用户选择打印的组或者主机
            try:
                _t = raw_input("\033[1;32mG/g or H/h>:\033[0m ").strip()
                if _t == 'q':
                    break
            except (IndexError, ValueError):
                color_print('错误输入')
            if _t in ['G', 'g']:
                user_asset_group_all = get_group_user_perm(self.user).get(
                    'asset_group', [])
                color_print('[%-3s] %-20s %s' % ('ID', '组名', '备注'), 'title')
                for asset_group in user_asset_group_all:
                    print '[%-3s] %-15s %s' % (
                        asset_group.id, asset_group.name, asset_group.comment)
                print
                try:
                    _gid = raw_input("\033[1;32mGid>:\033[0m ").strip()
                    if _gid == 'q':
                        break
                except (IndexError, ValueError):
                    color_print('错误输入')
                else:
                    _gid_pattern = re.compile(r'^\d+$')

                    if _gid_pattern.match(_gid):
                        gid = int(_gid.lstrip('g'))
                        # 获取资产组包含的资产
                        asset_group = get_object(AssetGroup, id=gid)
                        if asset_group and asset_group in self.perm_asset_groups:
                            _search_result = list(asset_group.asset_set.all())
                            print "授权包含该系统用户的所有主机(测试功能)"
                            #assets = []
                            if hasattr(_search_result, '__iter__'):
                                for index, asset in enumerate(_search_result):
                                    #assets_obj = [Asset.objects.get(id=asset_id) for asset_id in _search_result]
                                    #assets.append(assets_obj)
                                    print ' %s' % asset.hostname
                                print
                            #print(assets)
                            #print type(assets[0])
                        else:
                            color_print('没有该资产组或没有权限')
                            return
            else:
                assets = list(
                    self.user_perm.get(
                        'role', {}).get(role).get('asset'))  # 获取该用户,角色授权主机
                print "授权包含该系统用户的所有主机"
                for asset in assets:
                    print ' %s' % asset.hostname
                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)
                print(assets)
                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
コード例 #31
0
ファイル: content.py プロジェクト: vanwt/ttcmdb
    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 = 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]
            assets = list(self.user_perm.get('role', {}).get(role).get('asset'))  # 获取该用户,角色授权主机
            print
            "授权包含该系统用户的所有主机"
            for asset in assets:
                print
                ' %s' % asset.hostname
            print
            print("请输入主机名或ansile支持的pattern, 多个主机:分隔, q退出")
            pattern = 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 = input("\033[1;32mCmds>:\033[0m ").strip()
                    if command == 'q':
                        break
                    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()
コード例 #32
0
ファイル: connect.py プロジェクト: cn27001/jumpserver
    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]
            assets = list(self.user_perm.get("role", {}).get(role).get("asset"))  # 获取该用户,角色授权主机
            print "授权包含该系统用户的所有主机"
            for asset in assets:
                print " %s" % asset.hostname
            print
            print "请输入主机名或ansile支持的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
                    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
コード例 #33
0
ファイル: connect.py プロジェクト: cn27001/jumpserver
    def download(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "进入批量下载模式"
                print "请输入主机名或ansile支持的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
コード例 #34
0
ファイル: connect.py プロジェクト: 277800076/jumpserver
    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.hostname
            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
                    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
コード例 #35
0
ファイル: views.py プロジェクト: ljb-2000/jumpserver-1
def asset_list(request):
    """
    asset list view
    """
    header_title, path1, path2 = u'查看资产', u'资产管理', u'查看资产'
    username = request.user.username
    user_perm = request.session['role_id']
    idc_all = IDC.objects.filter()
    asset_group_all = AssetGroup.objects.all()
    asset_types = ASSET_TYPE
    asset_status = ASSET_STATUS
    idc_name = request.GET.get('idc', '')
    group_name = request.GET.get('group', '')
    asset_type = request.GET.get('asset_type', '')
    status = request.GET.get('status', '')
    keyword = request.GET.get('keyword', '')
    export = request.GET.get("export", False)
    group_id = request.GET.get("group_id", '')
    idc_id = request.GET.get("idc_id", '')
    asset_id_all = request.GET.getlist("id", '')

    if group_id:
        group = get_object(AssetGroup, id=group_id)
        if group:
            asset_find = Asset.objects.filter(group=group)
    elif idc_id:
        idc = get_object(IDC, id=idc_id)
        if idc:
            asset_find = Asset.objects.filter(idc=idc)
    else:
        if user_perm != 0:
            asset_find = Asset.objects.all()
        else:
            asset_id_all = []
            user = get_object(User, username=username)
            asset_perm = get_group_user_perm(user) if user else {'asset': ''}
            user_asset_perm = asset_perm['asset'].keys()
            for asset in user_asset_perm:
                asset_id_all.append(asset.id)
            asset_find = Asset.objects.filter(pk__in=asset_id_all)
            asset_group_all = list(asset_perm['asset_group'])

    if idc_name:
        asset_find = asset_find.filter(idc__name__contains=idc_name)

    if group_name:
        asset_find = asset_find.filter(group__name__contains=group_name)

    if asset_type:
        asset_find = asset_find.filter(asset_type__contains=asset_type)

    if status:
        asset_find = asset_find.filter(status__contains=status)

    if keyword:
        asset_find = asset_find.filter(
            Q(hostname__contains=keyword) |
            Q(other_ip__contains=keyword) |
            Q(ip__contains=keyword) |
            Q(remote_ip__contains=keyword) |
            Q(comment__contains=keyword) |
            Q(username__contains=keyword) |
            Q(group__name__contains=keyword) |
            Q(cpu__contains=keyword) |
            Q(memory__contains=keyword) |
            Q(disk__contains=keyword) |
            Q(brand__contains=keyword) |
            Q(cabinet__contains=keyword) |
            Q(sn__contains=keyword) |
            Q(system_type__contains=keyword) |
            Q(system_version__contains=keyword))

    if export:
        if asset_id_all:
            asset_find = []
            for asset_id in asset_id_all:
                asset = get_object(Asset, id=asset_id)
                if asset:
                    asset_find.append(asset)
        s = write_excel(asset_find)
        if s[0]:
            file_name = s[1]
        smg = u'excel文件已生成,请点击下载!'
        return my_render('jasset/asset_excel_download.html', locals(), request)
    assets_list, p, assets, page_range, current_page, show_first, show_end = pages(asset_find, request)
    if user_perm != 0:
        return my_render('jasset/asset_list.html', locals(), request)
    else:
        return my_render('jasset/asset_cu_list.html', locals(), request)
コード例 #36
0
ファイル: connect.py プロジェクト: cn27001/jumpserver
    def upload(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "进入批量上传模式"
                print "请输入主机名或ansile支持的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_dir), 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
コード例 #37
0
def asset_list(request):
    """
    asset list view
    """
    header_title, path1, path2 = u'查看资产', u'资产管理', u'查看资产'
    username = request.user.username
    user_perm = request.session['role_id']
    idc_all = IDC.objects.filter()
    asset_group_all = AssetGroup.objects.all()
    asset_types = ASSET_TYPE
    asset_status = ASSET_STATUS
    idc_name = request.GET.get('idc', '')
    group_name = request.GET.get('group', '')
    asset_type = request.GET.get('asset_type', '')
    status = request.GET.get('status', '')
    keyword = request.GET.get('keyword', '')
    export = request.GET.get("export", False)
    group_id = request.GET.get("group_id", '')
    idc_id = request.GET.get("idc_id", '')
    asset_id_all = request.GET.getlist("id", '')
    sn = request.GET.get('sn', '')

    if group_id:
        group = get_object(AssetGroup, id=group_id)
        if group:
            asset_find = Asset.objects.filter(group=group)
    elif idc_id:
        idc = get_object(IDC, id=idc_id)
        if idc:
            asset_find = Asset.objects.filter(idc=idc)
    else:
        if user_perm != 0:
            asset_find = Asset.objects.all()
        else:
            asset_id_all = []
            user = get_object(User, username=username)
            asset_perm = get_group_user_perm(user) if user else {'asset': ''}
            user_asset_perm = asset_perm['asset'].keys()
            for asset in user_asset_perm:
                asset_id_all.append(asset.id)
            asset_find = Asset.objects.filter(pk__in=asset_id_all)
            asset_group_all = list(asset_perm['asset_group'])

    if idc_name:
        asset_find = asset_find.filter(idc__name__contains=idc_name)

    if group_name:
        asset_find = asset_find.filter(group__name__contains=group_name)

    if asset_type:
        asset_find = asset_find.filter(asset_type__contains=asset_type)

    if status:
        asset_find = asset_find.filter(status__contains=status)
    if sn:
        asset_find = asset_find.filter(status__contains=sn)

    if keyword:
        asset_find = asset_find.filter(
            Q(hostname__contains=keyword) | Q(other_ip__contains=keyword)
            | Q(ip__contains=keyword) | Q(remote_ip__contains=keyword)
            | Q(comment__contains=keyword) | Q(username__contains=keyword)
            | Q(group__name__contains=keyword) | Q(cpu__contains=keyword)
            | Q(memory__contains=keyword) | Q(disk__contains=keyword)
            | Q(brand__contains=keyword) | Q(cabinet__contains=keyword)
            | Q(sn__contains=keyword) | Q(system_type__contains=keyword)
            | Q(system_version__contains=keyword))

    if export:
        if asset_id_all:
            asset_find = []
            for asset_id in asset_id_all:
                asset = get_object(Asset, id=asset_id)
                if asset:
                    asset_find.append(asset)
        s = write_excel(asset_find)
        if s[0]:
            file_name = s[1]
        smg = u'excel文件已生成,请点击下载!'
        return my_render('jasset/asset_excel_download.html', locals(), request)
    assets_list, p, assets, page_range, current_page, show_first, show_end = pages(
        asset_find, request)
    if user_perm != 0:
        return my_render('jasset/asset_list.html', locals(), request)
    else:
        return my_render('jasset/asset_cu_list.html', locals(), request)