简体   繁体   English

使用 zipfile 读取受密码保护的 Word 文档

[英]Reading password protected Word Documents with zipfile

I am trying to read a password protected word document on Python using zipfile.我正在尝试使用 zipfile 阅读 Python 上受密码保护的 word 文档。 The following code works with a non-password protected document, but gives an error when used with a password protected file.以下代码适用于不受密码保护的文档,但在使用受密码保护的文件时会出错。

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)

When running get_docx_text() with a password protected file, I received the following error:使用受密码保护的文件运行 get_docx_text() 时,我收到以下错误:

Traceback (most recent call last):追溯(最近一次通话):

  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

Does anyone have any advice to get this code to work?有没有人有任何建议让这段代码工作?

I don't think this is an encryption problem, for two reasons:我不认为这是一个加密问题,原因有二:

  1. Decryption is not attempted when the ZipFile object is created.创建ZipFile object 时不会尝试解密。 Methods like ZipFile.extractall , extract , and open , and read take an optional pwd parameter containing the password, but the object constructor / initializer does not. ZipFile.extractallextractopen以及read等方法采用包含密码的可选pwd参数,但 object 构造函数/初始化程序没有。

  2. Your stack trace indicates that the BadZipFile is being raised when you create the ZipFile object, before you call setpassword :您的堆栈跟踪表明在您调用setpassword之前创建ZipFile BadZipFile时正在引发 BadZipFile :

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

I'd look carefully for other differences between the two files you're testing: ownership, permissions, security context (if you have that on your OS), ... even filename differences can cause a framework to "not see" the file you're working on.我会仔细查看您正在测试的两个文件之间的其他差异:所有权、权限、安全上下文(如果您的操作系统上有),...甚至文件名差异也会导致框架“看不到”该文件你正在努力。

Also --- the obvious one --- try opening the encrypted zip file with your zip-compatible command of choice.另外 --- 显而易见的 --- 尝试使用您选择的与 zip 兼容的命令打开加密的 zip 文件。 See if it really is a zip file.看看是不是真的zip文件。

I tested this by opening an encrypted zip file in Python 3.1, while "forgetting" to provide a password.我通过在 Python 3.1 中打开一个加密的 zip 文件来测试这个,同时“忘记”提供密码。 I could create the ZipFile object (the variable zfile below) without any error, but got a RuntimeError --- not a BadZipFile exception --- when I tried to read a file without providing a password:我可以创建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

I was also able to raise a BadZipfile exception, once by trying to open an empty file and once by trying to open some random logfile text that I'd renamed to a ".zip" extension.我还能够引发BadZipfile异常,一次是通过尝试打开一个空文件,一次是通过尝试打开一些我已重命名为“.zip”扩展名的随机日志文件文本。 The two test files produced identical stack traces, down to the line numbers.这两个测试文件产生了相同的堆栈跟踪,包括行号。

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

While this stack trace isn't exactly the same as yours --- mine has a call to _GetContents , and the pre-3.2 "small f" spelling of BadZipfile --- but they're close enough that I think this is the kind of problem you're dealing with.虽然这个堆栈跟踪与你的不完全相同——我的有一个对_GetContents的调用,以及BadZipfile的 3.2 之前的“small f”拼写——但它们足够接近,我认为这就是那种你正在处理的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM