Search code examples
python-2.7zip

Python - Password Protecting Zip folders


The script currently creates a zip folder at the current working directory, and populates it with the currently signed-in user files (e.g. "Documents and Settings\Owner*". However, I'm wanting to password protect the zip folder; I've checked on here for viable responses but they're either old posts, or were unconfirmed by the person posting the question.

So, How can I password protect a zip file thats already created in python?

My Current code;

import os, zipfile, getpass, sys

try:
    user= getpass.getuser()
    print " [*] Creating a zip-folder in current working directory...\r"
    zf = zipfile.ZipFile(user + ".zip", "w", zipfile.ZIP_DEFLATED)
    sys.__stdout__
    directory = "C:\\Documents and Settings\\Owner"
    print " [*] Created successfully..."
    print" [*] Attempting to copy files...\r"
    for dirname, subdirs, files in os.walk(directory):
        sys.stdout.write(" [*] Now copying files...\r")
        if "Local Settings" in files:
                continue
        zf.write(dirname)
        for filename in files:
            if "NTUSER" in filename:
                continue
            elif "ntuser" in filename:
                continue
            elif user + ".zip" in filename:
                continue
            elif "UsrClass" in filename:
                continue
            zf.write(os.path.join(dirname, filename))
    print ' [*] Completed copying files to zip-file...'
except IOError as e:
    print ' [-] ' + e
except KeyboardInterrupt:
    print ' [-] Cancelling current operation'
    sys.exit(0)
zf.close()

Solution

  • From the docs:

    It [this module] supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file

    So unfortunately you can't encrypt a zip using the zipfile module.