簡體   English   中英

使用 zipfile 讀取受密碼保護的 Word 文檔

[英]Reading password protected Word Documents with zipfile

我正在嘗試使用 zipfile 閱讀 Python 上受密碼保護的 word 文檔。 以下代碼適用於不受密碼保護的文檔,但在使用受密碼保護的文件時會出錯。

try:
    from xml.etree.cElementTree import XML
except ImportError:
    from xml.etree.ElementTree import XML
import zipfile

psw = "1234"

WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'

def get_docx_text(path):

    document = zipfile.ZipFile(path, "r")
    document.setpassword(psw)
    document.extractall()
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.getiterator(PARA):
        texts = [node.text
                 for node in paragraph.getiterator(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return '\n\n'.join(paragraphs)

使用受密碼保護的文件運行 get_docx_text() 時,我收到以下錯誤:

追溯(最近一次通話):

  File "<ipython-input-15-d2783899bfe5>", line 1, in <module>
runfile('/Users/username/Workspace/Python/docx2txt.py', wdir='/Users/username/Workspace/Python')

  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 680, in runfile
execfile(filename, namespace)

  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)

  File "/Users/username/Workspace/Python/docx2txt.py", line 41, in <module>
x = get_docx_text("/Users/username/Desktop/file.docx")

  File "/Users/username/Workspace/Python/docx2txt.py", line 23, in get_docx_text
document = zipfile.ZipFile(path, "r")

  File "zipfile.pyc", line 770, in __init__

  File "zipfile.pyc", line 811, in _RealGetContents

BadZipfile: File is not a zip file

有沒有人有任何建議讓這段代碼工作?

我不認為這是一個加密問題,原因有二:

  1. 創建ZipFile object 時不會嘗試解密。 ZipFile.extractallextractopen以及read等方法采用包含密碼的可選pwd參數,但 object 構造函數/初始化程序沒有。

  2. 您的堆棧跟蹤表明在您調用setpassword之前創建ZipFile BadZipFile時正在引發 BadZipFile :

    document = zipfile.ZipFile(path, "r")

我會仔細查看您正在測試的兩個文件之間的其他差異:所有權、權限、安全上下文(如果您的操作系統上有),...甚至文件名差異也會導致框架“看不到”該文件你正在努力。

另外 --- 顯而易見的 --- 嘗試使用您選擇的與 zip 兼容的命令打開加密的 zip 文件。 看看是不是真的zip文件。

我通過在 Python 3.1 中打開一個加密的 zip 文件來測試這個,同時“忘記”提供密碼。 我可以創建ZipFile object(下面的變量zfile )而沒有任何錯誤,但是當我嘗試在不提供密碼的情況下讀取文件時出現RuntimeError ---而不是BadZipFile異常 --- :

Traceback (most recent call last):
  File "./zf.py", line 35, in <module>
    main()
  File "./zf.py", line 29, in main
    print_checksums(zipfile_name)
  File "./zf.py", line 22, in print_checksums
    for checksum in checksum_contents(zipfile_name):
  File "./zf.py", line 13, in checksum_contents
    inner_file = zfile.open(inner_filename, "r")
  File "/usr/lib64/python3.1/zipfile.py", line 903, in open
    "password required for extraction" % name)
RuntimeError: File apache.log is encrypted, password required for extraction

我還能夠引發BadZipfile異常,一次是通過嘗試打開一個空文件,一次是通過嘗試打開一些我已重命名為“.zip”擴展名的隨機日志文件文本。 這兩個測試文件產生了相同的堆棧跟蹤,包括行號。

Traceback (most recent call last):
  File "./zf.py", line 35, in <module>
    main()
  File "./zf.py", line 29, in main
    print_checksums(zipfile_name)
  File "./zf.py", line 22, in print_checksums
    for checksum in checksum_contents(zipfile_name):
  File "./zf.py", line 10, in checksum_contents
    zfile = zipfile.ZipFile(zipfile_name, "r")
  File "/usr/lib64/python3.1/zipfile.py", line 706, in __init__
    self._GetContents()
  File "/usr/lib64/python3.1/zipfile.py", line 726, in _GetContents
    self._RealGetContents()
  File "/usr/lib64/python3.1/zipfile.py", line 738, in _RealGetContents
    raise BadZipfile("File is not a zip file")
zipfile.BadZipfile: File is not a zip file

雖然這個堆棧跟蹤與你的不完全相同——我的有一個對_GetContents的調用,以及BadZipfile的 3.2 之前的“small f”拼寫——但它們足夠接近,我認為這就是那種你正在處理的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM