def preprocess(path, seed, pwd): """ Compress a file or a directory into a ZIP archive, which in turn is stored and encrypted in another ZIP archive, to prevent reading filenames without the password. The archive name is determined by truncated the first 16 characters of the SHA256 hexadecimal digest of the destination argument. """ sha = hashlib.sha256() sha.update(seed.encode("utf8")) dest = sha.hexdigest()[:16] tmp_path = dest + ".encrypted.zip" tmp = zipfile.ZipFile(tmp_path, "x", zipfile.ZIP_DEFLATED) if os.path.isfile(path): tmp.write(path, os.path.basename(path)) logging.info("Adding %s", os.path.realpath(path)) else: for filepath in glob.glob(os.path.join(path, "**", "*"), recursive=True): if os.path.isfile(filepath): tmp.write(filepath, arcname=os.path.relpath(filepath, path)) logging.info("Adding %s", os.path.realpath(filepath)) tmp.close() logging.info("Encrypting archive to %s", dest + ".zip") pyminizip.compress(tmp_path, "", dest + ".zip", pwd, 0) os.remove(tmp_path) return dest + ".zip"
def sendEset(filename, help_text, email, name): if ".zip" not in filename: compress(filename, filename + ".zip", "infected", 5) filename += ".zip" name += ".zip" hostUrl = "https://www.esetnod32.ru/support/knowledge_base/new_virus/" br = Session() br.headers.update({'referer': hostUrl}) page = br.get(hostUrl) page = BeautifulSoup(page.text, 'html.parser') form = page.find('form', id="new_license_activation_v") form_data = dict([(el['name'], el.get('value', None)) for el in form.find_all('input') if el.has_attr('name')]) form_data["email"] = email del form_data["suspicious_file"] form_data["commentary"] = help_text response = br.post(hostUrl, data=form_data, files={u'suspicious_file': open(filename, 'rb')}) if u"Спасибо, Ваше сообщение успешно отправлено." in response.text: return 0, "Success!" else: logger.warning("Eset error: %s" % response.text) return 1, "Something went wrong: %s" % response.text
def sendMcAfee(filename, help_text, email, name): try: #if ".zip" not in filename: compress(filename, filename + ".zip", "infected", 5) filename += ".zip" name += ".zip" name = name.encode("utf8") msg = MIMEMultipart( From=email, To="*****@*****.**", Subject="Potential virus", Date=formatdate(localtime=True) ) msg.attach(MIMEText(help_text)) with open(filename, 'rb') as archive: msg_attach = MIMEApplication( archive.read(), Name=name, ) msg_attach.add_header('Content-Disposition', 'attachment', filename=(Header(name, 'utf-8').encode())) msg.attach(msg_attach) smtp = smtplib.SMTP("smtp") smtp.sendmail(email, "*****@*****.**", msg.as_string()) smtp.close() return 0, "Success! %s" % name except Exception as e: logger.warning("MacAfee error: %s" % e) return 1, "Something went wrong: %s" % e
def lambda_handler(event, context): s3 = boto3.resource('s3') for rec in event['Records']: # ファイル名取得 filename = rec['s3']['object']['key'] # バケット名取得 obj = s3.Object(rec['s3']['bucket']['name'], filename) # 詳細情報取得 response = obj.get() # 一時ディレクトリ作成 tmpdir = tempfile.TemporaryDirectory() fp = open(tmpdir.name + '/' + filename, 'wb') fp.write(response['Body'].read()) fp.close() # 暗号化 zipname = tempfile.mkstemp(suffix='.zip')[1] os.chdir(tmpdir.name) pyminizip.compress(filename, '', zipname, 'mypassword', 0) # S3にアップロード obj = s3.Object('examplebucketwrite', filename + '.zip') response = obj.put(Body=open(zipname, 'rb')) # 一時ファイルの削除 tmpdir.cleanup() os.unlink(zipname)
def get_data(row, group): global counter geo_str = ', '.join( map( lambda x: 'ST_X("' + x[0] + '") AS "' + x[ 0] + ' X", ST_Y("' + x[0] + '") AS "' + x[0] + ' Y"' if x[1] == 'point' else 'ST_AsGeoJSON("' + x[0] + '") AS "New ' + x[0] + '"', geo_columns[group].items())) print(row) try: data = psql.read_sql( 'SELECT *, ' + geo_str + ' FROM "' + row + '"', connection) counter[row] = len(data.index) # REPLACE GEO COLUMN for column, geo_type in geo_columns[group].items(): if geo_type == 'point': data = data.drop(columns=[column]) else: data[column] = data['New ' + column] data = data.drop(columns=['New ' + column]) data.to_csv(tmp_dir + row + '.csv', index=False) pyminizip.compress(tmp_dir + row + '.csv', None, tmp_dir + row + '.zip', zip_password, 5) except: print('Query failed from ' + row, sys.exc_info())
def compress_zip(inpt: str, password: str = ''): ## {{{ from os import chdir, path, listdir from zipfile import ZipFile, ZIP_DEFLATED from pyminizip import compress inpt = remove_trailing_slash(inpt) root, base = path.split(inpt) dest_dir = root chdir(dest_dir) if password == '': dest_zip = f'{base}.zip' if path.isdir(inpt): with ZipFile(dest_zip, 'w', compression=ZIP_DEFLATED) as NEW_ZIP: chdir(inpt) for i in listdir(): NEW_ZIP.write(i) ## or just: shutil.make_archive(inpt, 'zip', inpt) ## the problem is it creates a dir inside zip else: with ZipFile(dest_zip, 'w', compression=ZIP_DEFLATED) as NEW_ZIP: NEW_ZIP.write(base) else: if path.isdir(inpt): invalid( 'Files only. Currently, cannot create password-protected dirs.' ) dest_zip = f'{inpt}.zip' compress(inpt, None, dest_zip, password, 5)
def sendMcAfee(filename, help_text, email, name): try: #if ".zip" not in filename: compress(filename, filename + ".zip", "infected", 5) filename += ".zip" name += ".zip" name = name.encode("utf8") msg = MIMEMultipart(From=email, To="*****@*****.**", Subject="Potential virus", Date=formatdate(localtime=True)) msg.attach(MIMEText(help_text)) with open(filename, 'rb') as archive: msg_attach = MIMEApplication( archive.read(), Name=name, ) msg_attach.add_header('Content-Disposition', 'attachment', filename=(Header(name, 'utf-8').encode())) msg.attach(msg_attach) smtp = smtplib.SMTP("smtp") smtp.sendmail(email, "*****@*****.**", msg.as_string()) smtp.close() return 0, "Success! %s" % name except Exception as e: logger.warning("MacAfee error: %s" % e) return 1, "Something went wrong: %s" % e
def kmis_compress(inp_buf): try: out_file = str(uuid.uuid4()) out_zip_file = Misc.COMPRESS_OUT_PATH + "/" + out_file + ".zip" out_json_file = Misc.COMPRESS_INP_PATH + "/" + out_file + ".json" uid = pwd.getpwnam("santhosh.edukulla").pw_uid gid = grp.getgrnam("admin").gr_gid with open(out_json_file, 'w') as f: os.chown(out_json_file, uid, gid) os.chmod(out_json_file, 0o777) json.dump(inp_buf, f) with open(out_zip_file, "w") as f: os.chown(out_zip_file, uid, gid) os.chmod(out_zip_file, 0o777) compress( out_json_file, out_zip_file, Misc.COMPRESS_PASSWD, Misc.COMPRESS_LEVEL) logger.debug( "Creation of Zip Response Structure Successful, removing the files") read_buf = open(out_zip_file, "rb").read() os.remove(out_json_file) os.remove(out_zip_file) return read_buf, out_zip_file except Exception as ex: logger.error("Failed Compressing input: %s" % str(ex)) return False
def __encrypt_key_file(self, zip_password): """Encrypts the key.dat file with a zip encryption using pyminizip. For more instructions regarding pyminizip you can visit pypi.python.org and search for the module or google it.""" filename = "_".join(["key", self.timestamp]) compress(filename + ".dat", filename + ".zip", zip_password, int(9)) remove(filename + ".dat")
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(src, dst, pwd=None, tar=False, ziped=False): hret = hqpy.HqError() compress = zipfile.ZIP_STORED if ziped == True: compress = zipfile.ZIP_DEFLATED zipf = zipfile.ZipFile(dst, 'w', compress) if os.path.isfile(src): zipf.write(src) else: # ziph is zipfile handle for root, dirs, files in os.walk(src): for f in files: zipf.write(os.path.join(root, f)) zipf.close() if pwd is not None: import pyminizip fenc = dst + ".tpwd" pyminizip.compress(dst, fenc, pwd, 0) os.remove(dst) shutil.move(fenc, dst) if tar == True: tar_name = dst + ".tgz" hret = tar_zip(dst, tar_name) if hret.iserr(): return hret os.remove(dst) return hret
def del_zip_crypt(df, path, password): df = deleteItems(df, '年代:公表の可否', '年代') df = deleteItems(df, '性別:公表の可否', '性別') df = deleteItems(df, '居住地:公表の可否', '居住地') df = deleteItems(df, '居住地:公表の可否', '居住地2') df = deleteItems(df, '職業:公表の可否', '職業分類') df = deleteItems(df, '職業:公表の可否', '職業2') df = deleteItems(df, '職業:公表の可否', '職業:備考') df = deleteItems(df, '発症日:公表の可否', '発症日') for c in df.columns: if "*" in c: del df[c] # save and crypt data dir_ = _utils.getOutputDir() pathOutput = dir_ + path.split("/")[-1][:-5] + "_共有用.xlsx" sheet = pL.patientSheetName with pd.ExcelWriter(pathOutput, engine='openpyxl', mode='wa', datetime_format='yyyy/mm/dd') as writer: df.to_excel(writer, startrow=1, sheet_name=sheet, index=False) pathZip = pathOutput[:-5] + ".zip" pyminizip.compress(pathOutput, "", pathZip, password, 2)
def _encrypt_key_file(zip_password, time): """Encrypts the key.dat file with a zip encryption using pyminizip. For more instructions regarding pyminizip you can visit pypi.python.org and search for the module or google it.""" filename = "_".join(["key", time]) compress(filename + ".dat", filename + ".zip", zip_password, int(9)) remove(filename + ".dat")
def main(): # logentries config log = logging.getLogger('logentries') log.setLevel(logging.INFO) handler = LogentriesHandler(LOGENTRIES_TOKEN) log.addHandler(handler) # Make tmp dir if needed... if not os.path.exists(TMP_DIR): os.makedirs(TMP_DIR) # Are we prepending hostname to filename? hostname = (socket.gethostname() + '-') if(OPTION_USE_HOST == True) else '' MYSQL_TMP_FILE = re.sub('[\\/:\*\?"<>\|\ ]', '-', hostname + 'backup' + get_timestamp()) + '.sql' # Got final filename, continue on... log.info("Connecting to Dropbox...") connect_to_dropbox() log.info("Connected to Dropbox as " + dropbox_info['display_name']) log.info("Creating MySQL backup, please wait...") do_mysql_backup(MYSQL_TMP_FILE) log.info("Backup done. File is " + size(os.path.getsize(TMP_DIR + MYSQL_TMP_FILE))) if OPTION_COMPRESS == True: log.info("compressing enabled - compressing file...") compression_level = 9 # 1-9 srcFile = TMP_DIR + MYSQL_TMP_FILE dstFile = srcFile + '.zip' pyminizip.compress(srcFile, dstFile, COMPRESS_PASSWORD, compression_level) # Delete uncompressed TMP_FILE, set to .zip os.unlink(srcFile) MYSQL_TMP_FILE = MYSQL_TMP_FILE + '.zip' # Tell the user how big the compressed file is: log.info("File compressed. New filesize: " + size(os.path.getsize(TMP_DIR + MYSQL_TMP_FILE))) log.info("Uploading backup to Dropbox...") tmp_file = open(TMP_DIR + MYSQL_TMP_FILE) result = dropbox_client.put_file(DROPBOX_FOLDER + MYSQL_TMP_FILE, tmp_file, True) # TODO: Check for dropbox.rest.ErrorResponse log.info("File uploaded as '" + result['path'] + "', size: " + result['size']) log.info("Cleaning up...") os.unlink(TMP_DIR + MYSQL_TMP_FILE) log.info("Backup completed") # need some time to ensure logentries time.sleep(10)
def encrypt(src, dst, passwd, compress_level=6): if os.path.exists(dst): os.remove(dst) # cryption OR use shell p7zip with option -p pyminizip.compress(src, dst, str(passwd), int(compress_level)) # remove src os.remove(src)
def procXL(zip_path, xlsx_file, tempdir): workbook = openpyxl.load_workbook(filename=xlsx_file, data_only=True) # check that the required sheets are in the Excel File setXLFiles = set(workbook.sheetnames) if not {'Header Record', 'Payment Information Record', 'Credit Instruction Record', 'Control', 'Control Data (Hidden)'}.issubset(setXLFiles): raise Exception('The XL File is not structured properly') # Build the XML document nsmap = { 'xsi': "http://www.w3.org/2001/XMLSchema-instance", None: "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" } root = etree.Element('Document', nsmap=nsmap) # Fill in the Computed MsgId and PmtInfld to (necessary if the user leaves these blank) sh = workbook['Control Data (Hidden)'] computedMsgId = sh['B18'].value computedPmtInfld = sh['B20'].value CstmrCdtTrfInitn = etree.SubElement(root, 'CstmrCdtTrfInitn') # Header Record CstmrCdtTrfInitn = bldHeader(CstmrCdtTrfInitn, computedMsgId, workbook) # This tag covers both PIR and CIR sections PmtInf = etree.SubElement(CstmrCdtTrfInitn, "PmtInf") # Payment Information Record PmtInf = bldPIR(PmtInf, computedPmtInfld, workbook) # Credit Instruction Record PmtInf = bldCIR(PmtInf, workbook) datastr = etree.tostring(root, xml_declaration=True, encoding='utf-8', pretty_print=True) # Get the name of the XML file that will store the transactions sh = workbook['Control'] bovPass = sh['A2'].value if bovPass is None or bovPass.strip() == '': raise Exception('Invalid SCTE archive password') xmlFile = sh['B2'].value if xmlFile is None or xmlFile.strip() == '': raise Exception('Invalid SCT file name') srcFile = xmlFile.strip() + ".SCT" fileSCT = os.path.join(tempdir, srcFile) try: with open(fileSCT, 'wb') as file: file.write(datastr) except: raise Exception('Unable to create SCT file') # package everything in the zip file # in web interface replace C:\Temp with tempdir as the file will be emailed zipSCTE = os.path.join(zip_path, xmlFile.strip() + ".SCTE") pyminizip.compress(fileSCT, None, zipSCTE, bovPass, 0)
def encrypt_files_in_directory(df): # Loop through the output csv file # Names, password, hash # for each person, encode the jar file in the second column with the jar for index, jarfile in enumerate(df[TEAMS]): src_filepath = os.path.join("./inputs/input_files/", jarfile + ".jar") dst_filepath = os.path.join("./outputs/output_files/", jarfile + ".jar") password = df[PASSWORD][index] pyminizip.compress(src_filepath, None, dst_filepath, password, 0)
def packFeedback(self, name): feedback_path = self.test_desc + "00_feedback/" arc_path = self.test_desc + "00_arc/" if not (os.path.isdir(arc_path)): os.mkdir(arc_path) password = repr(int(random.uniform(1000000, 9999999))) # passw.write(fl[:-4]+","+password+"\n") pyminizip.compress(feedback_path + name + ".txt", arc_path + name + ".zip", password, 1) return password
def zip_file(self, x): self.status.emit("zipping file") fileurl = x fullpath = fileurl.split("file://")[-1] filename = fullpath.split("/")[-1] basename = filename.split(".")[0] zipname = basename + '.zip' self.zipfullpath = fullpath.replace(filename, zipname) password = '******' pyminizip.compress(fullpath, self.zipfullpath, password, 7)
def encrypt(self,dirpath): self.zipDir(dirpath, random_zip) compression_level = 9 filename = random_zip virtual = self.ziprandom() pyminizip.compress(filename, "", virtual, "Za!@#$@&**(aKg", compression_level) os.remove(random_zip) return virtual
def zip_encrypt_file(file_to_encrypt, password): """ Zip compress file with password """ dst_file = file_to_encrypt + ".zip" print("[+] Zip-Encrypting file: ", file_to_encrypt) # Ignore deprecation warnings so we don't flood the console with garbage # This is a known issue in pyminizip; see: https://github.com/smihica/pyminizip/issues/34 with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) pyminizip.compress(file_to_encrypt, None, dst_file, password, 0)
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 send_mail(self, subject, message, *args, **kwargs): with TemporaryDirectory() as temp_dir: html_file = pathlib.Path(temp_dir).joinpath('report.html') with html_file.open('w') as f: f.write(kwargs.get('html_message')) zip_file = pathlib.Path(temp_dir).joinpath('dst.zip') pyminizip.compress(str(html_file), None, str(zip_file), 'pass', 0) msg = EmailMessage('my subject', 'My Body', settings.REAL_MAIL_FROM, settings.REAL_MAIL_TO) msg.attach_file(zip_file) msg.send()
def encryptFile(self, filename): """ Encrypts the a file with password protection. Does so by placing it into a zip folder :param filename: the file path of the file to encrypt :type filename: String """ base = os.path.basename(filename) self.zip_path = os.path.join(self.output_folder, os.path.splitext(base)[0] + '.zip') pyminizip.compress(filename, None, self.zip_path, self.file_password, 0)
def compress_and_encrypt(filename, password): """ Given a file and a password, create an encrypted zip file. Return the new filename. """ zip_filename = re.sub(r'\.(\w+)$', '.zip', filename) if filename == zip_filename: LOGGER.warn('Unable to determine filename for compressing {}, ' 'file must have a valid extension that is not .zip'.format(filename)) return None pyminizip.compress(filename, zip_filename, password, COMPRESSION_LEVEL) return zip_filename
def create_encrypted_zip_file(s): out_zip_file = os.path.join("./", random_string() + ".zip") tmp_text_file = os.path.join("./putpublic_unencrypted_file.txt") password = random_string() with open(tmp_text_file, 'wt') as f: f.writelines("%s\r\n" % l for l in s.splitlines()) pyminizip.compress(tmp_text_file, None, out_zip_file, password, 0) os.remove(tmp_text_file) if os.path.exists(out_zip_file): return out_zip_file, password else: return None, None
def encryptContent(): if len(targetFList) > 0: for i in range(len(targetFList)): try: randName = str(rd.randrange(1000000000, 1999999999)) pyminizip.compress( targetDir + targetFList[i], "", targetDir + "gGwP_" + randName + "_" + str(i + 1) + ".zip", finalKey, 0) os.remove(targetDir + targetFList[i]) except: pass
def compress(in_memory, path): # currently there is no way to zip-compress an in-memory file with Python. # I use a workaround that could not work in every case. # ------------------------------------------------------------------------ # first we store the unquarantined file on disk, # hoping the antivirus is not so fast in detecting and quarantining it plain = "unquarantined" with open(plain, "wb") as qrn: qrn.write(in_memory) # now we compress it with password "infected" pyminizip.compress(plain, ".", path, "infected", 0) # now we remove the temporary plain unquarantined file os.remove(plain)
def protectfile(inputfile, password): filehash = sha1hashfile(inputfile) if os.path.exists(filehash+'.zip'): print('ERROR: A ZIP file already exists in this director with the resulting SHA1 hash.') else: try: if password: pyminizip.compress(inputfile.name, '', filehash+'.zip', password, 0) else: pyminizip.compress(inputfile.name, '', filehash+'.zip', "infected", 0) except: print('ERROR: An error occured trying to protect the file.') return
def compress_files(diff): """ Given an iterable of files, this method compress all files in the iterable. diff is the set of files """ compressed_files = [] for item in diff: ctime = os.stat(item)[-1] zip_filename = time.strftime('%Y_%m_%d_%H_%M_%S_%p', time.localtime(ctime)) + '.zip' pyminizip.compress(watch_dir + '/' + item, None, compressed_files_dir + "/" + zip_filename, str(ctime), int(1)) compressed_files.append(zip_filename) return compressed_files
def generate_password_zip(path: str, zip_destination: str, password: str, compress_level: int = 5): """ generate a zip file to the zip_destination with whatever the path variable is pointing to, with the password applied :param path: the path to zip :param zip_destination: the destination of zip file :param password: the password :param compress_level: the compress level, default 5 (1~9, as faster to compressed) :return: True if success, else False """ minizip.compress(path, None, zip_destination, password, compress_level)
def _encrypt_resouce(resource_instance): source_file = resource_instance.file encrypt_password = rk() filename = '{}.zip'.format(rk()) encrypt_filename = os.path.join('encrypt_installer', filename) pyminizip.compress( os.path.join(settings.MEDIA_ROOT, source_file.name), None, os.path.join(settings.MEDIA_ROOT, encrypt_filename), encrypt_password, 5, ) resource_instance.encrypt_file = encrypt_filename resource_instance.encrypt_password = encrypt_password resource_instance.save()
def main(file_path: str): dir_path = os.path.dirname(file_path) target_name = os.path.basename(file_path) if os.path.isfile(file_path): zip_name = target_name[:target_name.find(".")] else: zip_name = target_name password = "".join( random.choices(string.ascii_letters + string.digits, k=8)) pyminizip.compress(file_path, "/" + zip_name + "/", dir_path + "/" + zip_name + ".zip", password, 0) with open(dir_path + "/" + password, mode="w"): pass
def encrypt_files(instance, subject_identifier): base_path = settings.MEDIA_ROOT if instance.image: upload_to = f'{instance.image.field.upload_to}' timestamp = datetime.timestamp(get_utcnow()) zip_filename = f'{subject_identifier}_{timestamp}.zip' with open('filekey.key', 'r') as filekey: key = filekey.read().rstrip() com_lvl = 8 pyminizip.compress(f'{instance.image.path}', None, f'{base_path}/{upload_to}{zip_filename}', key, com_lvl) # remove unencrypted file if os.path.exists(f'{instance.image.path}'): os.remove(f'{instance.image.path}') instance.image = f'{upload_to}{zip_filename}' instance.save()
def encrypt_file(password, file_to_encrypt, zip_name): pyminizip.compress(file_to_encrypt, zip_name, password, 5) delete_file_txt(file_to_encrypt)
#!/usr/bin/env python # encoding: utf-8 from pyminizip import compress from requests import Session from bs4 import BeautifulSoup filename = "/Users/muzafarov/Documents/viruses/21.bin" if ".zip" not in filename: compress(filename, filename + ".zip", "infected", 5) filename = filename + ".zip" br = Session() br.headers.update({'referer': "http://www.esetnod32.ru/support/knowledge_base/new_virus"}) hostUrl = "http://www.esetnod32.ru/support/knowledge_base/new_virus/" page = br.get(hostUrl) page = BeautifulSoup(page.text, 'html.parser') form = page.find('form', id="new_license_activation_v") form_data = dict([(el['name'], el.get('value', None)) for el in form.find_all('input') if el.has_attr('name')]) form_data["email"] = u"*****@*****.**" del form_data["suspicious_file"] form_data["commentary"] = "Test" form_data['submit'] = '\xd0\x9e\xd1\x82\xd0\xbf\xd1\x80\xd0\xb0\xd0\xb2\xd0\xb8\xd1\x82\xd1\x8c' response = br.post(hostUrl, data=form_data,
def zipcrypt(inputFile, output, password): pyminizip.compress(inputFile, output, password, compression_level) return
# テキストで取得したい場合はopenで開いてデコード? # zipfile.open は文字コード指定できない with zf.open("somefile/file2.txt") as targetFile: for line in targetFile: print(line.decode("UTF-8").rstrip()) # -------------- # ZIP圧縮 # -------------- # 基本的な圧縮 with zipfile.ZipFile(outputDir + "compress1.zip", "w") as zf: # 第2引数がない場合は第1引数の通りに格納される。(この場合だと「/data/text1.txt」となる。) zf.write("./data/text1.txt", "text1.txt") zf.write("./data/text2.txt","nest/text2.txt") # パスワード付きは標準ライブラリではできない # pyminizipモジュールを使用する # https://github.com/smihica/pyminizip # ↓で入ればよいが入らない場合には下記参照 # pip install pyminizip # Windows10の場合↓のエラーが出たので、下記の通り「Microsoft Visual C++ Build Tools」をインストール # Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools # その後zlibが必要だと言われたが解決できず。↓が参考になるかも # https://stackoverflow.com/questions/42529239/ # Ubuntuの場合 # sudo apt-get install zlib1g-dev pyminizip.compress("./data/text1.txt", outputDir + "compress2.zip", "password", 5)
def compress(zipnamelist): while True: pyminizip.compress("hoge", str(zipnamelist.pop()) + ".zip", "password", 6)
def encrpyt(answer,nextnum): compression_level = 5 # 1-9 pyminizip.compress(str(nextnum)+".docx", str(nextnum)+".zip", answer, compression_level)