Python中给unzip传AES解密zip流报错及临时zip自动删除方案咨询
解决方案
方案1:现有临时文件逻辑加自动清理
你无法在解压的同时删除临时zip文件:unzip运行过程中需要持续读取zip文件的物理内容,提前删除会导致解压直接失败。你可以等解压进程执行完成后再删除临时文件,Python实现代码如下:
import subprocess import os temp_zip_path = f"{inputFile}.zip" # 完成解密写入临时文件 with open(temp_zip_path, "wb") as output_f: decrypt_proc = subprocess.Popen( ['openssl', 'enc', '-d', '-aes-256-cbc', '-md', 'sha256', '-in', inputFile, '-pass', f'pass:{passw_hash}'], stdout=output_f ) decrypt_proc.wait() # 阻塞等待解密完成 # 执行解压 unzip_proc = subprocess.Popen(['unzip', temp_zip_path, '-d', path_dict[0]]) unzip_proc.wait() # 阻塞等待解压完成 # 删除临时zip文件 os.remove(temp_zip_path)
如果你希望把删除逻辑和解压命令写在同一行,可以调用shell来执行串联命令:
subprocess.run( f"unzip {temp_zip_path} -d {path_dict[0]} && rm -f {temp_zip_path}", shell=True, check=True )
注意:shell=True存在命令注入风险,仅当你确认所有路径、参数都是可控的场景下使用
方案2:无需临时文件的替代实现(更推荐)
原生unzip不支持标准输入流读取的本质问题,可以通过替换解压工具为7z解决,7z原生支持从stdin读取压缩包内容,全程不会生成临时文件,也就不需要额外做删除操作:
decrypt_proc = subprocess.Popen( ['openssl', 'enc', '-d', '-aes-256-cbc', '-md', 'sha256', '-in', inputFile, '-pass', f'pass:{passw_hash}'], stdout=subprocess.PIPE ) decompress_proc = subprocess.Popen( ['7z', 'x', '-si', f'-o{path_dict[0]}', '-y'], stdin=decrypt_proc.stdout ) decrypt_proc.stdout.close() decompress_proc.wait()
参数说明:
-si:指定7z从标准输入读取压缩包内容-o后直接拼接目标路径,中间不要加空格-y:自动确认所有提示,无需人工交互
如果你的系统没有预装7z,可以通过对应包管理器安装:
- Debian/Ubuntu系列:
apt install p7zip-full - CentOS/RHEL系列:
yum install p7zip - macOS:
brew install p7zip
内容的提问来源于stack exchange,提问作者Dev Dev
相关产品推荐
相关产品推荐

