Example #1
0
    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
Example #2
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
Example #3
0
    def upload(self):
        while True:
            try:
                print "进入批量上传模式"
                print
                print "授权包含该系统用户的所有主机"
                assets = self.user_perm.get('asset').keys()
                for asset in assets:
                    print ' %s' % asset.hostname
                print
                print "请输入主机名或ansible支持的pattern, 多个主机:分隔 q退出"
                print
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == 'q':
                    break
                else:
                    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.username, name=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
Example #4
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())
Example #5
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_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
Example #6
0
def upload(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', '')
        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, 'wb+') 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' % (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 = '上传目录: %s <br> 上传失败: [ %s ] <br>上传成功 [ %s ]' % (
                upload_dir, ', '.join(list(ret.get('failed').keys())),
                ', '.join(list(ret.get('ok').keys())))
            return HttpResponse(error, status=500)
        msg = '上传目录: %s <br> 传送成功 [ %s ]' % (upload_dir, ', '.join(
            list(ret.get('ok').keys())))
        return HttpResponse(msg)
    return my_render('upload.html', locals(), request)
Example #7
0
    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
Example #8
0
    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