开发者

is it possible to check if pdf is password protected using ghostscript?

is it possible to check if pdf is password protected using ghostscript? what would be the command? 开发者_如何转开发 I know you can strip pdf password using ghostscript, but all I want to do is just checking if PDF is password protected or security enabled.


checkuserpasswdPDF.sh:

#!/bin/sh

GS=~/gs/bin/gs
output=`$GS -dBATCH -sNODISPLAY "$1" 2>&1`
gsexit=$?

if [ "$gsexit" == "0" ]; then
  echo "Not user-password protected"
  exit 0;
else
  found=`echo "$output" |grep -o "This file requires a password"`
  if [ -z "$found" ]; then
    echo "Failed to invoke gs" 
    exit $gsexit
  else
    echo "Protected"
    exit 0;
  fi  
fi

Checks for user-password protected PDFs: checkuserpasswdPDF.sh test.pdf.

GS disregards owner-passwords (see this).


With pdftk it is possible to detect a user password or owner password by just trying to do a dump_data operation.

 protected=0
 pdftk "input.pdf" dump_data output /dev/null dont_ask || protected=1

The problem here is that you don't know what the password prevents: reading, extracting data, modifying...?


Using a bat file, you can do a little workaround by searching for "Encrypt" in the pdfs. Its quiet fast to search through many files.

Findstr /M /I "Encrypt" *.pdf 

This will return all filenames that are secured (since "Encrypt" will be written in the file as dos reads it)

Maybe this is something someone can use. I use:
for /f %%a in ('Findstr /M /I "Encrypt" *.pdf') do move %%a c:\tempfiles\
to move all secured pdf's to c:\tempfiles. From there I use ghostscript to remove the security, and move it back to original folder.


You can test using pdfinfo

pdfinfo $filename &>/dev/null;
if [[ $? -eq 1 ]] ; then
   echo "File can not be opened for reading"
fi


The answer of @Benoit gives ugly errors on console, but works.

So I would put this to an oneliner with suppression of error output:

protected=0 && pdftk "input.pdf" dump_data output /dev/null dont_ask 2>/dev/null || protected=1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜