Skip to content

Instantly share code, notes, and snippets.

@therohitdas
Last active January 1, 2024 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therohitdas/c490ec858b01ac889e9cdce7546541bd to your computer and use it in GitHub Desktop.
Save therohitdas/c490ec858b01ac889e9cdce7546541bd to your computer and use it in GitHub Desktop.
Extracts multiple password protected PDFs into a new directory
#!/bin/python3
"""
How to use?
1) pip3 install pikepdf
2) save all pdfs in the same folder as the script
3) run the script using - python3 process.py <pdf_password>
4) all the extracted passwords will be stored in /extracted
"""
import argparse
import pikepdf
import os
# Set up command line argument parsing
parser = argparse.ArgumentParser(description='Open PDFs with provided passwords.')
parser.add_argument('passwords', metavar='P', type=str, nargs='*',
help='one or more passwords to try')
args = parser.parse_args()
# If no passwords are provided, print help message and exit
if not args.passwords:
parser.print_help()
exit()
# Find all pdfs in current directory
pdfs = [f for f in os.listdir() if f.lower().endswith('.pdf')]
print("Found " + str(len(pdfs)) + " pdfs")
# Make directory
if not os.path.exists('extracted'):
os.makedirs('extracted')
# Try to open each PDF with each password
for pdf in pdfs:
for password in args.passwords:
try:
with pikepdf.open(pdf, password=password) as pdf_file:
# Save in extracted directory
pdf_file.save(os.path.join('extracted', pdf))
print("Extracted " + pdf)
break # If the PDF was successfully opened, stop trying passwords
except pikepdf.PasswordError:
continue # If the password was incorrect, try the next one
else:
print(f"Failed to open {pdf} with provided passwords.")
@therohitdas
Copy link
Author

Using this script, you can quickly unlock all the PDFs you want. This is useful if a lot of pdfs have the same password.
Helpful to open password-locked documents like credit card bills, official government documents etc.

usage -

index.py password1 password2 password3

Enter all the passwords at once, the script will try unlocking the pdfs with all the passwords provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment