def zip_files(file1, file2, password, cert_dir): zip_name = basename(file1).split('.')[0] + '.zip' cert_dir = join(cert_dir, 'tmp') zip_name_dir = join(cert_dir, zip_name) compress_multiple([file1, file2], [], zip_name_dir, password, 4) return cert_dir, zip_name
def quit_and_save(self): zip_files = globals()["zip_files"] options = globals()["options"] password = globals()["password"] test_list = globals()["test_list"] zip_files[-1][1] = test_list for i in zip_files: f = open(i[0], 'wb') pickle.dump(i[1], f) f.close() empty_array = [] i = 0 while i < len(zip_files): empty_array.append("") i += 1 if os.path.exists("myzip.zip"): os.remove("myzip.zip") print(options) print(zip_files) pyminizip.compress_multiple(options, empty_array,"myzip.zip", password, 2) for i in zip_files: os.remove(i[0]) self.destroy()
def _create_archive(self, archive_filename): if self.compression == 'zip': output_extension = 'zip' if support_passworded_zip and self.password: pyminizip.compress_multiple(self.filepaths, archive_filename, self.password, 1) else: with zipfile.ZipFile(archive_filename, 'w') as zFile: for path in self.filepaths: basename = os.path.basename(path) zFile.write(path, basename) return output_extension if self.compression == 'gz': output_extension = 'tgz' f = tarfile.open(archive_filename, 'w:gz') elif self.compression == 'bz2': output_extension = 'tar.bz2' f = tarfile.open(archive_filename, 'w:bz2') elif self.compression in ('tar', 'none'): output_extension = 'tar' f = tarfile.open(archive_filename, 'w') for path in self.filepaths: basename = os.path.basename(path) f.add(path, basename) f.close() return output_extension
def zip(self, user, password): from django.contrib.auth import authenticate user = authenticate(username=user.username, password=password) if user is None: raise SystemError(u'密碼輸入不正確') custom_epub = self.path + '/temp/{0}_{1}.epub'.format( self.ISBN, user.username) if not os.path.exists(os.path.dirname(custom_epub)): os.mkdir(os.path.dirname(custom_epub)) custom_epub = self.custom_epub_create(custom_epub, user) #加入壓縮檔內 import pyminizip custom_zip = self.path + '/temp/{0}_{1}.zip'.format( self.ISBN, user.username) zip_list = [custom_epub] try: pyminizip.compress_multiple(zip_list, custom_zip, password, 5) return custom_zip except BaseException as e: try: os.remove(custom_zip) except BaseException as e: raise SystemError('zip create fail remove dirname' + unicode(e)) raise SystemError('zip create fail:' + unicode(e))
def archive(self, path=None, password=None, ask=False, remove=True, **kwargs): """ This method compresses the content of the given source path into the given archive as the destination path, eventually given a password. :param path: path to the project folder to be archived :param password: password string to be passed :param ask: whether a password should be asked or not :param remove: remove after compression """ if self.is_archive: raise ValueError("Already an archive") password = getpass() if ask else password dst = Path(path or (str(self) + ".zip")) src_list, dst_list = [], [] for f in self.walk(filter_func=lambda p: p.is_file()): src_list.append(str(f)) dst_list.append(str(f.relative_to(self).dirname)) # Pyminizip changes the current working directory after creation of an archive ; so backup the current # working directory to restore it after compression cwd = os.getcwd() compress_multiple(src_list, dst_list, str(dst), password or "", 9) os.chdir(cwd) if remove: self.remove() return ProjectPath(dst)
async def inflate_archive(self, file_ids, fileformat, name, password=None): try: # TODO: will in future support multiple files instead of string ids? file_ids = file_ids.split() print("picking {}".format(file_ids)) # GET all items from shuffle items = [self.get_file(file_id) for file_id in file_ids] if len(items) == 0: return "No file to inflate" # Dump files on disk, because libs want path :( with tempfile.TemporaryDirectory() as tmpdir: paths = [] print("Number 1") for item in items: with open(os.path.join(tmpdir, item["filename"]), "wb") as f: f.write(item["data"]) paths.append(os.path.join(tmpdir, item["filename"])) # Create archive temporary print("{} items to inflate".format(len(items))) with tempfile.NamedTemporaryFile() as archive: if fileformat == "zip": archive_name = "archive.zip" if not name else name pyminizip.compress_multiple( paths, [], archive.name, password, 5 ) elif fileformat == "7zip": archive_name = "archive.7z" if not name else name with py7zr.SevenZipFile( archive.name, "w", password=password if len(password) > 0 else None, ) as sz_archive: for path in paths: sz_archive.write(path) else: return "Format {} not supported".format(fileformat) return_id = self.set_files( [{"filename": archive_name, "data": open(archive.name, "rb")}] ) if len(return_id) == 1: # Returns the first file's ID return {"success": True, "id": return_id[0]} else: return { "success": False, "message": "Upload archive returned {}".format(return_id), } except Exception as excp: return {"success": False, "message": excp}
def ZipFileBegin(tree, settings): children = tree.get_children() srcFileList = list() for c in children: srcFileList.append(tree.item(c)["values"][2]) dstFilePath = settings[0].get() key = settings[2].get() keyAgain = settings[3].get() if keyAgain != key: messagebox.showerror('Σ(っ °Д °;)っ', '密码不一致,请重新输入!') return zipLevelStr = settings[1].get() # 选择压缩等级, 默认为正常压缩 3 if zipLevelStr == "0-不压缩": zipLevel = 0 elif zipLevelStr == "1-快速压缩": zipLevel = 3 elif zipLevelStr == "2-正常压缩": zipLevel = 6 else: zipLevel = 9 messagebox.showinfo(" ̄へ ̄", "压缩已经开始,请耐心等待...") pyminizip.compress_multiple(srcFileList, [], dstFilePath, key, zipLevel) srcFileSize = 0 for file in srcFileList: srcFileSize += os.path.getsize(file) dstFileSize = os.path.getsize(dstFilePath) zipRate = "%(rate).4f" % {'rate': (dstFileSize / srcFileSize) * 100} + "%" messagebox.showinfo( "o(* ̄▽ ̄*)ブ", "压缩成功!!!\n压缩前文件大小: %s B\n压缩后文件大小: %s B\n压缩率为: %s" % (srcFileSize, dstFileSize, zipRate))
def zip_it(file_name, password): # 原文件路径 # 压缩文件解压后的文件夹名称 # zip文件名 # 密码 # 速度 compress_level(int) between 1 to 9, 1 (more fast) <---> 9 (more compress) or 0 (default) pyminizip.compress_multiple(path, spath, (file_name + '.zip'), password, 0)
def __init__(self, file_list, password=None, *args, **kwargs): # _zip_o = Ziper() # # for _file_path in file_list: # if os.path.exists(_file_path): # with open(_file_path) as file_o: # file_content = file_o.read() # # file_name_idx = _file_path.rfind('/') + 1 # file_name = _file_path[file_name_idx:] # # _zip_o.add(file_name, file_content) # # zf = zipfile.ZipFile(_zip_o.in_memory_zip, mode='r') # zf.setpassword('wwww') # zf.close() tmp_name = "/tmp/{}.zip".format(str(uuid.uuid4())) if len(file_list) == 0: _zip_o = Ziper() content = _zip_o.read() else: pyminizip.compress_multiple(file_list, tmp_name, password, 4) content = None with open(tmp_name) as _t: content = _t.read() os.remove(tmp_name) super(MultipleFileResponse, self).__init__(content, *args, **kwargs)
def _generate_zip(self, zip_name, password): """ パスワード付きZipファイルのデータを生成 """ tmp_dir = "/tmp/" + zip_name os.mkdir(tmp_dir) # 一旦ローカルにファイルを保存 for attach_file in self.email_attr['attach_files']: f = open(tmp_dir + "/" + attach_file['name'], 'wb') f.write(attach_file['data']) f.flush() f.close() # パスワード付きzipに dst_file_path = "/tmp/%s.zip" % zip_name src_file_names = ["%s/%s" % (tmp_dir, name) for name in os.listdir(tmp_dir)] pyminizip.compress_multiple(src_file_names, dst_file_path, password, 4) # # 生成したzipファイルを読み込み r = open(dst_file_path, 'rb') zip_data = r.read() r.close() return zip_data
def compress(files, basedir, name, password): zipname = os.path.join(basedir, name) LOGGER.info("Creating archive {}".format(zipname)) pyminizip.compress_multiple( [os.path.join(basedir, file) for file in files], os.path.join(basedir, name), password, 4) return zipname
def compress_withpw(self, srcpath, dstname, password='', compress_level=3): '''加密压缩''' #single file compress if os.path.isfile(srcpath) is True: pyminizip.compress(srcpath, dstname, password, compress_level) return True if os.path.isdir(srcpath) is True: files_list = [] for root, dirs, files in os.walk(srcpath): if dirs: break for name in files: files_list.append(os.path.join(root, name).encode('utf-8')) #empty directory compress if files_list is False: return False #Single-level directory if files_list: pyminizip.compress_multiple(files_list, dstname, password, compress_level) return True #Multi-level directory else: tmp_zip_file = "/tmp/tmp.zip" self.compress(srcpath, tmp_zip_file) pyminizip.compress(tmp_zip_file, dstname, password, compress_level) os.remove(tmp_zip_file)
def zip(self, user, password, format): from django.contrib.auth import authenticate user = authenticate(username=user.username, password=password) if user is None: raise SystemError(u'密碼輸入不正確') custom_path = self.path + '/temp/{0}_{1}.{2}'.format( self.ISBN, user.username, format) if not os.path.exists(os.path.dirname(custom_path)): os.makedirs(os.path.dirname(custom_path)) if format == 'epub': custom_path = self.custom_epub_create(custom_path, user) elif format == 'txt': custom_path = self.custom_txt_create(custom_path, user) return custom_path #加入壓縮檔內 import pyminizip custom_zip = self.path + '/temp/{0}_{1}.zip'.format( self.ISBN, user.username) zip_list = [custom_path] try: pyminizip.compress_multiple(zip_list, [], custom_zip, password, 5) return custom_zip except BaseException as e: raise SystemError('zip create fail:' + str(e)) try: os.remove(custom_zip) except BaseException as e: raise SystemError('zip create fail remove dirname' + str(e)) raise SystemError('zip create fail:' + str(e))
def zip(self, user, password, format): from django.contrib.auth import authenticate user = authenticate(username=user.username, password=password) if user is None: raise SystemError(u'密碼輸入不正確') custom_path = self.path +'/temp/{0}_{1}.{2}'.format(self.ISBN, user.username, format) if not os.path.exists(os.path.dirname(custom_path)): os.mkdir(os.path.dirname(custom_path)) if format == 'epub': custom_path = self.custom_epub_create(custom_path, user) elif format == 'txt': custom_path = self.custom_txt_create(custom_path, user) #加入壓縮檔內 import pyminizip custom_zip = self.path +'/temp/{0}_{1}.zip'.format(self.ISBN, user.username) zip_list = [custom_path] try: pyminizip.compress_multiple(zip_list, custom_zip, password, 5) return custom_zip except BaseException as e: try: os.remove(custom_zip) except BaseException as e: raise SystemError('zip create fail remove dirname' +unicode(e)) raise SystemError('zip create fail:' +unicode(e))
def archive_files(dir_path, archive_name, password): """ Archives all files(no dirs) in a given directory. Stores the archive in a 'archive' subdir :param dir_path: str path to directory with files :param archive_name: str name of the archive without path. Zip extension is added if missing :param password: str archive password :return: str path """ files_to_archive = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))] # prefix is a literal file_prefix = "data" file_prefixes = [file_prefix for _ in files_to_archive] if not str.endswith(archive_name, ".zip"): archive_name = archive_name + ".zip" archive_dir_name = "archived" archive_dir = os.path.join(dir_path, archive_dir_name) utils.ensure_dir(archive_dir) archive_path = os.path.join(archive_dir, archive_name) logger.info('archiving files{}'.format(files_to_archive)) pyminizip.compress_multiple(files_to_archive, file_prefixes, archive_path, password, 5) return archive_path
def compress_backup(filename, password, dbversion): with file("dbver", 'w') as f: f.write(str(dbversion)) pyminizip.compress_multiple([filename, 'dbver'], 'tmp.zip', password, 9) os.remove('dbver')
def __create_outer_zip(self): inner_image_path_1 = os.path.join(self.tmp_dir, INNER_IMAGE_FILENAME_1) inner_image_path_2 = os.path.join(self.tmp_dir, INNER_IMAGE_FILENAME_2) inner_zip_path = os.path.join(self.tmp_dir, INNER_ZIP_FILENAME) outer_zip_path = os.path.join(self.tmp_dir, OUTER_ZIP_FILENAME) pyminizip.compress_multiple( [inner_image_path_1, inner_image_path_2, inner_zip_path], ['', '', ''], outer_zip_path, None, 9)
def compress(files, basedir, name, password): zipname = os.path.join(basedir, name) LOGGER.info("Creating archive {}".format(zipname)) pyminizip.compress_multiple( [os.path.join(basedir, file) for file in files], os.path.join(basedir, name), password, 4 ) return zipname
def compress(self, file): if os.path.exists(file): path, name = os.path.split(file) name, ext = name.split(".") with self.stopwatch('compress'): pyminizip.compress_multiple([u'%s' % file], path + "/" + name + "." + ext + ".zip", self.createPassword(), 4) return True else: return False
def create_zip(files, zip_name, output_path, password): zip_path = os.path.join(output_path, zip_name) try: if len(files) == 1: single = files[0] pyminizip.compress(single, zip_path, password, 1) else: pyminizip.compress_multiple(files, zip_path, password, 1) except: return sys.exc_info()
def generate_zip(self): if not settings.OBIEE_ZIP_PASSWORD: raise DjangoImproperlyConfigured("OBIEE zip password must be set.") with remember_cwd(): try: os.chdir(self.tmp_export_path) pyminizip.compress_multiple(glob.glob("*.csv"), [], self.filename, settings.OBIEE_ZIP_PASSWORD, 9) shutil.move( "%s/%s" % (self.tmp_export_path, self.filename), "%s/%s" % (self.export_path, self.filename) ) finally: shutil.rmtree(self.tmp_export_path)
def generate_zip(self): if not settings.OBIEE_ZIP_PASSWORD: raise DjangoImproperlyConfigured("OBIEE zip password must be set.") with remember_cwd(): try: os.chdir(self.tmp_export_path) pyminizip.compress_multiple(glob.glob("*.csv"), [], self.filename, settings.OBIEE_ZIP_PASSWORD, 9) shutil.move("%s/%s" % (self.tmp_export_path, self.filename), "%s/%s" % (self.export_path, self.filename)) finally: shutil.rmtree(self.tmp_export_path)
def generatePackage(imagefile, documentfile, audiofile, outputfile, secret, identifier): if not os.path.exists("static/rdt"): os.mkdir("static/rdt/") inputfiles = [] inputfiles.append(imagefile) inputfiles.append(documentfile) inputfiles.append(audiofile) print inputfiles try: pyminizip.compress_multiple(inputfiles, outputfile, secret, 5) except Exception as ex: print ex
def zip_full(self, ): from django.contrib.auth import authenticate import pyminizip zip_file_name = BASE_DIR +'/file/ebookSystem/document/{0}/OCR/{1}.zip'.format(self.book.book_info.ISBN, self.ISBN_part, ) zip_list = [self.get_path(), self.get_path('-edit'), self.get_path('-finish'), ] try: pyminizip.compress_multiple(zip_list, zip_file_name, '', 5) return zip_file_name except BaseException as e: try: os.remove(zip_file_name) raise e except: raise e
def compress_to_desktop(self): """ Compress files to user desktop :return: output path """ cur_time = str( datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d-%H-%M-%S')) output_path = '{desktop_path}\\SamplePack[{time}].zip'.format( desktop_path=os.path.expanduser("~\\Desktop"), time=cur_time) self.output_path = output_path pyminizip.compress_multiple(self.file_list, [], output_path, self.password, 8) return output_path
def compress(self): """ Compress files to user dir :return: output path """ cur_time = str( datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d-%H-%M-%S')) user_path = os.getenv('APPDATA') + "\\VirusSampleSubmitter" output_path = '{user_path}\\SamplePack[{time}].zip'.format( user_path=user_path, time=cur_time) self.output_path = output_path pyminizip.compress_multiple(self.file_list, [], output_path, self.password, 8) return output_path
def run(): parser = get_argument_parser() args = parser.parse_args() config = ConfigParser.ConfigParser() config.read(args.config) if args.zipname: out_name = args.zipname else: try: out_name = get_out_name(args.files) except: out_name = '{}.zip'.format(os.path.basename(args.files[0])) pyminizip.compress_multiple( args.files, os.path.join(config.get('out', 'out_dir'), out_name), args.password, 4)
def run(): parser = get_argument_parser() args = parser.parse_args() config = ConfigParser.ConfigParser() config.read(args.config) if args.zipname: out_name = args.zipname else: try: out_name = get_out_name(args.files) except: out_name = '{}.zip'.format(os.path.basename(args.files[0])) pyminizip.compress_multiple( args.files, os.path.join(config.get('out', 'out_dir'), out_name), args.password, 4 )
def create_savelist(output_path, **criteria): """Function used to create a zip file containing songs given keyword args criteria""" import pyminizip if not output_path.endswith('.zip'): print('output_path not zip') exit(0) query_result = db.query_db(**criteria) if query_result == 0: print('No data found') else: files = [] for row in query_result: files.append('Storage/' + row[1]) pyminizip.compress_multiple(files, [], output_path, "1233", 4) print('Files added succesfully') pass
def down_log(request): sz_file = request.query_params.get('file') if not sz_file: raise exceptions.ValidationError({"file not none"}) file_list = [] log_parent_path = logset.get_log_parent_path() if sz_file: file_list = sz_file.split(',') file_list = [os.path.join(log_parent_path, a) for a in file_list] # 创建加密文件路径 tmp_name = "/tmp/{}.zip".format(str(uuid.uuid4())) pyminizip.compress_multiple(file_list, [], tmp_name, api_settings.LOG_ZIP_PASSWORD, 4) response = TmpFileResponse(tmp_name) response['content-Disposition'] = 'attachment; filename=log.zip' return response
def addTemps(msg, obj, dir, updir, outpath): zip = obj['zip'] zippw = obj['zippw'] files = obj['files'] for o in files: filename = o['filename'] outfile = outpath + '/' + filename convert_b64_string_to_file(o['data'], outfile) if zip is None or zip == False: ext = filename.split(".")[-1] if os.path.isfile(outfile): attach = MIMEApplication(open(outfile, 'rb').read(), _subtype=ext) attach.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attach) if zip is not None and (zip == True or str(zip).lower() == 'true'): os.chdir(updir) zipname = dir + '_zip.zip' if zippw is None or len(zippw) <= 0: with zipfile.ZipFile(zipname, 'w', compression=zipfile.ZIP_STORED) as n_zip: for file in os.listdir(dir): n_zip.write(os.path.join(dir, file)) else: src = [] level = 4 for file in os.listdir(dir): src.append(os.path.join(dir, file)) pyminizip.compress_multiple(src, [], zipname, zippw, level) os.chdir('../') if os.path.isfile(updir + zipname): attach = MIMEBase('application', 'zip') attach.set_payload(open(updir + zipname, 'rb').read()) encoders.encode_base64(attach) attach.add_header('Content-Disposition', 'attachment', filename=zipname) msg.attach(attach) return msg
def zip(self, user, password): from django.contrib.auth import authenticate import pyminizip user = authenticate(username=user.username, password=password) if user is None: return False custom_zip = self.book.path +'/temp/{0}_{1}.zip'.format(self.ISBN_part, user.username) if not os.path.exists(os.path.dirname(custom_zip)): os.mkdir(os.path.dirname(custom_zip)) zip_list = [self.get_clean_file()] try: pyminizip.compress_multiple(zip_list, custom_zip, password, 5) return custom_zip except BaseException as e: try: os.remove(custom_zip) except BaseException as e: pass return False
def zip(self, user, password): from django.contrib.auth import authenticate import pyminizip user = authenticate(username=user.username, password=password) if user is None: return False custom_zip = self.book.path + '/temp/{0}_{1}.zip'.format( self.ISBN_part, user.username) if not os.path.exists(os.path.dirname(custom_zip)): os.makedirs(os.path.dirname(custom_zip)) zip_list = [self.get_clean_file()] try: pyminizip.compress_multiple(zip_list, custom_zip, password, 5) return custom_zip except BaseException as e: try: os.remove(custom_zip) except BaseException as e: pass return False
def zip_full(self, ): from django.contrib.auth import authenticate import pyminizip zip_file_name = BASE_DIR + '/file/ebookSystem/document/{0}/OCR/{1}.zip'.format( self.book.book_info.ISBN, self.ISBN_part, ) zip_list = [ self.get_path(), self.get_path('-edit'), self.get_path('-finish'), ] try: pyminizip.compress_multiple(zip_list, zip_file_name, '', 5) return zip_file_name except BaseException as e: try: os.remove(zip_file_name) raise e except: raise e
def pyminizip_compressor(dst_zip_file, project_configuration, log_dump=True, mongo_dump=True, sys_log_dump=True, password=None, compress_level=9): logger.info("[pyminizip_compressor][Utils][Using pyminizip compressor]") src_files_list = [] arc_names_list = [] remove_files = [] try: if log_dump: log_files, log_arc_names = get_logs(project_configuration) src_files_list.extend(log_files) arc_names_list.extend(log_arc_names) if mongo_dump: mongo_dump_files, mongo_dump_arc_names, remove_folder = get_mongodump(project_configuration) src_files_list.extend(mongo_dump_files) arc_names_list.extend(mongo_dump_arc_names) if remove_folder: remove_files.append(remove_folder) if sys_log_dump: sys_dump_files, sys_dump_arc_names, remove_file = get_sys_info_log(project_configuration) src_files_list.extend(sys_dump_files) arc_names_list.extend(sys_dump_arc_names) if remove_file: remove_files.extend(remove_file) par_arc_dirs = [os.path.dirname(arc_path) for arc_path in arc_names_list ] pyminizip.compress_multiple(src_files_list, par_arc_dirs, dst_zip_file, password, compress_level) except Exception as ex: logger.exception("[zipfile_compressor][Utils][Exception->{}]".format(ex)) for file_ in remove_files: if os.path.exists(file_): if os.path.isdir(file_): shutil.rmtree(file_) else: os.remove(file_)
def zip_files(ziphome, zipname, zippw, level): if ziphome is None: ziphome = './' if zipname is None: zipname = get_dir(None) + '_zip.zip' # print(os.getcwd()) print(ziphome) if zippw is None or len(zippw) <= 0: with zipfile.ZipFile(zipname, 'w', compression=zipfile.ZIP_STORED) as n_zip: for file in os.listdir(ziphome): n_zip.write(os.path.join(ziphome, file)) else: if level is None: level = 4 src = [] for file in os.listdir(ziphome): src.append(os.path.join(ziphome, file)) pyminizip.compress_multiple(src, [], zipname, zippw, level) return zipname
def pack_zip(cls, tmp_dir, password=None): """zip导出 :param tmp_dir: 临时目录 :param password: 打包密码 :return: zip导出文件路径 """ zip_file_path = '{}.zip'.format(tmp_dir) files = list_files(tmp_dir, True) file_prefixs = [] for file_path in files: file_dir = os.path.dirname(file_path) file_prefix = file_dir.replace(tmp_dir, '') or '/' file_prefixs.append(file_prefix) pyminizip.compress_multiple( files, file_prefixs, zip_file_path, password, 5, ) return zip_file_path