Python教程:如何解密解压ZIP、7z文件和读取PDF文件
引言
在日常工作和学习中,我们经常会遇到需要处理加密文件的情况,比如PDF文档、7z压缩包或ZIP文件。Python作为一种功能强大的编程语言,能够帮助我们轻松应对这些需求。今天,我们将通过一个实用的Python脚本,学习如何解密PDF文件、解密解压7z文件以及使用解密解压ZIP文件。
概览
这个脚本主要使用了PyPDF2
库来处理PDF文件,py7zr
库来解压7z文件,以及Python内置的zipfile
模块来处理ZIP文件。脚本的核心功能是通过命令行参数来指定文件路径、密码文件路径以及单个密码。
代码Gitee上的路径为:
https://gitee.com/ezemeti/z7pCryptX
使用get安装
git clone https://gitee.com/ezemeti/z7pCryptX.git
主要功能
-
1. 读取密码列表:从文本文件中读取密码列表。
-
2. 解密PDF:解密读取PDF文件。并且复制到新的pdf文件中
-
3. 解压7z文件:解密解压7z文件。
-
4. 解压ZIP文件:解密解压ZIP文件。
代码
导入模块
# 导入argparse模块,用于编写用户友好的命令行接口
import argparse
# 导入os模块,用于与操作系统交互,如文件和目录操作
import os
# 导入zipfile模块,用于处理ZIP压缩和解压缩文件
import zipfile
# 导入PyPDF2模块,用于处理PDF文件,如合并、拆分、旋转等
import PyPDF2
# 导入py7zr模块,用于处理7z压缩文件,这是一个Python的7-Zip实现
import py7zr
读取密码列表:
从文本文件中读取密码列表。
def read_passwords_from_file(passwords_file_path):
"""
从文本文件中读取密码列表。
:param passwords_file_path: 包含密码的文本文件路径
:return: 包含密码的列表
"""
try:
with open(passwords_file_path, 'r', encoding='utf-8') as file:
passwords = [line.strip() for line in file.readlines()]
return passwords
except FileNotFoundError:
print(f"文件 {passwords_file_path} 不存在。")
解压ZIP文件:
破解密码解压ZIP文件
def zip_with_password(zip_file_path, password):
"""
破解密码解压zip文件。
:param zip_file_path: ZIP文件路径
:param password: <PASSWORD>
"""
if type(password) == list:
for p in password:
try:
with zipfile.ZipFile(zip_file_path, 'r', zipfile.ZIP_STORED) as z:
z.extractall("./", pwd=p.encode("utf-8"))
print(f"密码正确: {p}")
break
except:
continue
else:
print("使用-t参数指定密码文件中的密码不匹配")
elif password is None:
try:
with zipfile.ZipFile(zip_file_path, 'r', zipfile.ZIP_STORED) as z:
z.extractall("./")
print("解压成功!")
except Exception as e:
print(f"需要密码,使用-p参数指定密码或者使用-t参数指定密码文件,报错:{e}")
else:
try:
with zipfile.ZipFile(zip_file_path, 'r', zipfile.ZIP_STORED) as z:
z.extractall("./", pwd=password.encode("utf-8"))
print("解压成功!")
except Exception as e:
print(f"密码报错,使用-p参数指定密码或者使用-t参数指定密码文件,报错:{e}")
解压7z文件:
破解密码解压7z文件。
def decompress_7z(file_path, password):
"""
解压7z文件。
:param file_path: 7z文件的路径
:param password: <PASSWORD>
:return: None
"""
if type(password) == list:
for p in password:
try:
with py7zr.SevenZipFile(file_path, mode='r', password=p) as archive:
archive.extractall("./")
print(f"解压成功,密码为:{p}")
break
except:
continue
else:
print("使用-t参数指定密码文件中的密码不匹配")
elif password is None:
try:
with py7zr.SevenZipFile(file_path, mode='r') as archive:
archive.extractall("./")
print(f"解压成功!")
except Exception as e:
print(f"解压失败,请检查文件是否损害!报错结果:{e}")
else:
try:
with py7zr.SevenZipFile(file_path, mode='r', password=password) as archive:
archive.extractall("./")
print("解压成功!")
except Exception as e:
print(f"密码错误,请检查密码是否正确!报错结果:{e}")
解密PDF:
解密PDF文件。
def decrypt_pdf(input_path, passwords):
"""
尝试用给定的密码列表解密PDF文件。
:param input_path: 需要解密的PDF文件路径
:param passwords: 密码列表或密码
"""
if type(passwords) == list:
for password in passwords:
try:
with open(input_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
if pdf_reader.is_encrypted:
pdf_reader.decrypt(password)
decrypted_file_path = "new_" + input_path
with open(decrypted_file_path, 'wb') as output_file:
writer = PyPDF2.PdfWriter()
for page_num in pdf_reader.pages:
writer.add_page(page_num)
writer.write(output_file)
print(f"成功解密,密码为:{password}")
break
except Exception as e:
print(f"使用密码'{password}'时出错:{e}")
else:
print("使用-t参数指定密码文件中的密码不匹配")
elif passwords is None:
try:
with open(input_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
if pdf_reader.is_encrypted:
print(f"文件{input_path}需要密码!")
else:
decrypted_file_path = "new_" + input_path
with open(decrypted_file_path, 'wb') as output_file:
writer = PyPDF2.PdfWriter()
for page_num in pdf_reader.pages:
writer.add_page(page_num)
writer.write(output_file)
except Exception as e:
print(f"打开文件时出错:{e}")
else:
with open(input_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
if pdf_reader.is_encrypted:
pdf_reader.decrypt(passwords)
decrypted_file_path = "new_" + input_path
with open(decrypted_file_path, 'wb') as output_file:
writer = PyPDF2.PdfWriter()
for page_num in pdf_reader.pages:
writer.add_page(page_num)
writer.write(output_file)
判断
判断zip,7z,pdf文件
def determine_action(file_path):
_, ext = os.path.splitext(file_path)
ext = ext.lower()
if ext == ".pdf":
return "解密PDF"
elif ext == ".7z":
return "解压7z"
elif ext in {".zip", ".rar"}:
return "加密zip"
else:
raise ValueError("不支持的文件类型:{}".format(ext))
执行函数
def main():
parser = argparse.ArgumentParser(description="处理PDF、7z和zip文件")
parser.add_argument("file_path", help="待处理文件的路径")
parser.add_argument("-t", "--passwords-file", default="passwords.txt",
help="包含密码的文本文件路径,每行一个密码。默认:passwords.txt")
parser.add_argument("-o", "--no-password", action="store_true",
help="指示文件无需密码")
parser.add_argument("-p", "--password", default=None,
help="明确指定单个密码")
args = parser.parse_args()
action = determine_action(args.file_path)
if args.no_password:
password = None
elif args.password:
password = args.password
else:
password = read_passwords_from_file(args.passwords_file)
if action == "解密PDF":
decrypt_pdf(args.file_path, password)
elif action == "解压7z":
decompress_7z(args.file_path, password)
elif action == "加密zip":
zip_with_password(args.file_path, password)
else:
raise ValueError("不支持的操作:{}".format(action))
if __name__ == "__main__":
main()
实操步骤
环境准备
首先,确保你的Python环境中已安装所需的库:
-
•
PyPDF2
-
•
py7zr
可以使用pip命令安装:
pip install PyPDF2 py7zr
运行脚本
将脚本保存为.py
文件,例如file_handler.py
。然后,通过命令行运行脚本并传入相应的参数:
python file_handler.py [文件路径] [-t 密码文件路径] [-o] [-p 密码]
参数说明:
-
•
[文件路径]
:待处理文件的路径。 -
•
[-t 密码文件路径]
:包含密码的文本文件路径,每行一个密码。默认为passwords.txt
。 -
•
[-o]
:指示文件无需密码。 -
•
[-p 密码]
:明确指定单个密码。
示例
-
1. 解密PDF文件:
python file_handler.py encrypted.pdf -t passwords.txt
-
2. 解压7z文件:
python file_handler.py archive.7z -p mypassword
-
3. 解压ZIP文件:
python file_handler.py compressed.zip -o
-
4. 说明
python file_handler.py -h
结语
通过这个Python脚本,我们可以方便地处理常见的加密文件。这不仅可以节省时间,还能提高工作效率。希望这个教程对你有所帮助,如果你有任何疑问或建议,欢迎在评论区交流!
原文始发于微信公众号(索隆程序员):Python教程:如何破解密码解压ZIP、7z和读取PDF文件
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/271275.html