需求场景: 当前目录下有一堆 zip,rar,7z,word,pdf 的加密或不加密的文件,同时也有一个密码本,现在需要将所有加密的文件解密。人工一个一个解密效率低头痛,故使用 python 制作了一个小工具,供自己使用。
import json
import os
import re
import subprocess
import PyPDF2
import win32com.client,time
passwordDict={}
def word_decryption(path, password):
dirname, tempname = os.path.split(path)
path_temp = os.path.join(dirname, "decrypt_"+tempname)
def decryption(fp, pt, pw):
try:
# 由于机器没有正版 Word,故使用 Wps 代替,如果需要使用 Word ,将下面的Kwps.application替换成Word.application 即可。
word_app = win32com.client.Dispatch("Kwps.application")
word_app.Visible = False
except Exception as e:
print("Wps Not Found")
return
try:
doc = word_app.Documents.Open(fp, False, False, False, pw)
doc.SaveAs2(pt, None, False, '')
except Exception as e:
print(e)
doc.Close()
word_app.Quit()
decryption(path, path_temp, password)
time.sleep(0.1)
def getPassword(current_directory):
#处理密码,保存到 passwordDict 字典中,省略。
passwordDict[filename]=password
def batch_decrypt_pdfs(path, password):
dirname, tempname = os.path.split(path)
output_path = os.path.join(dirname, "decrypt_"+tempname)
# 检查文件是否有密码
with open(path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
if reader.is_encrypted and password:
# 解密PDF文件并保存副本到输出目录
with open(path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
writer = PyPDF2.PdfWriter()
reader.decrypt(password)
for page in reader.pages:
writer.add_page(page)
with open(output_path, 'wb') as output_file:
writer.write(output_file)
else:
pass
def decrypt():
current_directory=os.getcwd()
getPassword(current_directory)
for filename in os.listdir(current_directory):
file_path = os.path.join(current_directory, filename)
password = passwordDict.get(filename)
if filename.endswith('.rar') or filename.endswith('.zip') or filename.endswith('.7z'):
print(f'decrypt {file_path}')
extract_path=os.path.splitext(file_path)[0]
os.makedirs(extract_path, exist_ok=True)
# 需下载winrar。下面的路径可以自己改
if password:
subprocess.run([r'C:\Program Files\WinRAR\winrar.exe','-y', 'x', f'-p{password}','-ibck' , file_path,'*.*',extract_path])
else:
subprocess.run([r'C:\Program Files\WinRAR\winrar.exe','-y', 'x', '-ibck' , file_path,'*.*',extract_path])
elif filename.endswith('.docx') and password:
print(f'decrypt {file_path} {password}')
word_decryption(file_path,password)
elif filename.endswith('.pdf') and password:
print(f'decrypt {file_path} {password}')
batch_decrypt_pdfs(file_path,password)
if __name__ == '__main__':
decrypt()