tar files and encrypt a list of folders in openssl in python

To tar files and encrypt a list of folders using OpenSSL in Python, you can use the tarfile and subprocess modules along with the OpenSSL command-line tool.

Here's an example code snippet that shows how to achieve this:

main.py
import tarfile
import subprocess

# list of folders to be tarred and encrypted
folders = ['/path/to/folder1', '/path/to/folder2', '/path/to/folder3']

# create a tar archive of the folders
with tarfile.open('folders.tar', 'w:gz') as tar:
    for folder in folders:
        tar.add(folder)

# encrypt the tar archive using OpenSSL
password = 'mysecretpassword'
subprocess.call(f'openssl aes-256-cbc -a -salt -pass pass:{password} -in folders.tar -out folders.tar.enc', shell=True)
480 chars
15 lines

In this example, we first create a tarfile object and add all the folders to it using the add() method. We then use the subprocess module to run the OpenSSL command-line tool and encrypt the tar archive using AES-256-CBC encryption and prompting for the password. The encrypted archive is saved as folders.tar.enc.

Note that you will need to have OpenSSL installed on your system to use this method. You can install it using your system's package manager or by downloading and installing it from the official OpenSSL website.

gistlibby LogSnag