user3352256
user3352256

Reputation: 109

preserving file permission when creating a tarball with Python's tarfile

hello stackoverflowers,

I want to preserve the original file permissions when using Python's tarfile module. I have quite a few executable files that lose their permissions once the tarball is extracted.

I'm doing something like this:

import tarfile
tar = tarfile.open("mytarball.tar.gz", 'w:gz')
tar.add('my_folder') #tar the entire folder 
tar.close()

Then I copy it from windows to a linux machine (mapped with samba) using shutil:

shutil.copy("mytarball.tar.gz",unix_dir)

Then, to extract the tarball in linux I do

unix>tar -xvf mytarball.tar.gz  

After the tarball is extracted I lose all the 'x' permissions on my files

Any clues how to solve this issue?

Regards

Upvotes: 6

Views: 5018

Answers (2)

Zenocode
Zenocode

Reputation: 702

Based on @DanGetz solution, I made this work for python3.8:

I'm using stream response to create the my tar file but here you're with the full code.

tar_stream = io.BytesIO()
tar = tarfile.TarFile(fileobj=tar_stream, mode='w')
file_data = content.encode('utf8')
tarinfo = tarfile.TarInfo(name=file_name)
tarinfo.size = len(file_data)
tarinfo.mtime = time.time()
tarinfo.mode = 0o740 # <--------
tar.addfile(tarinfo, io.BytesIO(file_data))
tar.close()

In python 2.6 and 3+ you must use this format for perissions: 0o777 instead of 0777.

from: https://stackoverflow.com/a/1627222/6809926

Upvotes: 1

Dan Getz
Dan Getz

Reputation: 9133

If you know which of your files should have execute permissions or not, you can set the permissions manually with a filter function:

def set_permissions(tarinfo):
    tarinfo.mode = 0777 # for example
    return tarinfo

tar.add('my_folder', filter=set_permissions)

Upvotes: 6

Related Questions