How do I remove passwords of some of all the pdf files in a directory with python?

Viewed 1701

I have some pdf files in a directory. Some of them are password protected, some of them are not. I know the passwords for each of the password protected files. How do I automate the process of removing passwords from each of the pdf files? I am thinking of something like:

  1. Getting the password protected file.
  2. Trying the given passwords from a wordlist I've made.
  3. Printing out the password for the file.
  4. Saving the file as 'Decrypted_filename.pdf'
4 Answers

I found a useful library, pikepdf, that is based on qpdf and automatically converts pdfs to be extractable.

The code to use this is pretty straightforward:

import pikepdf

pdf = pikepdf.open('unextractable.pdf')
pdf.save('extractable.pdf')

so as you want to remove the password, the password can be set with

pikepdf.open('unextractable.pdf', password='thepassword')

Try This:

import pikepdf
paths=[...] # path of all files
passwords=[...] # passwords 
outputPaths=[...] # output file path
for i in range(len(paths)):
    pdf = pikepdf.open(paths[i],password=passwords[i])
    pdf.save(outputPaths[i])

Note:

pip install pikepdf
If the file is not password protected then use :- pdf = pikepdf.open('NAME')

Figured it out!
Here is my code:

import pikepdf
import os
import shutil

# Load Wordlist
wordlist = input('Enter wordlist: ')
passwords = passwords = [ line.strip() for line in open(wordlist) ]

# Making Directory
try:
    os.mkdir('Decrypted')
except FileExistsError as e:
    pass

# iterate over passwords
def crack(p):
 if ".pdf" in str(p):
  #print('\nOpening: '+str(p))
  print(str(p))
  for password in passwords:
   try:
    # open PDF file
    with pikepdf.open(p, password=password) as pdf:
     # Password decrypted successfully, break out of the loop
     print("[+] Password found:", password)
     x=i.split('.pdf')[0]
     y=x+"_DECRYPTED.pdf"
     pdf.save(y)
     shutil.move(y, 'Decrypted')
     pdf.close()
     #os.remove(i)
     break
   except pikepdf._qpdf.PasswordError as e:
    # wrong password, just continue in the loop
    continue
 else:
  pass

for i in os.listdir(os.getcwd()):
 crack(i)

I think you can solve your problem with pyPdf

Related