The following code creates a new directory 'output' and extracts the tar archive given as argv in it. When a malformed archive (attached) is given as argv, a IsADirectoryError is thrown, as opposed to extracting the file contained in the archive to the 'output' directory.
Code:
import tarfile
import sys
import os
def extract(archive_path, destination_path):
if not tarfile.is_tarfile(archive_path):
print ('Not a tar file')
return
tar = tarfile.open(archive_path, 'r')
for info in tar.getmembers():
tar.extractall(destination_path, members=[tar.getmember(info.name)])
destination_path = 'output'
os.mkdir(destination_path)
extract(sys.argv[1], destination_path)
Result:
Traceback (most recent call last):
File "code.py", line 15, in <module>
extract(sys.argv[1], destination_path)
File "code.py", line 11, in extract
tar.extractall(destination_path, members=[tar.getmember(info.name)])
File "/usr/lib/python3.6/tarfile.py", line 2010, in extractall
numeric_owner=numeric_owner)
File "/usr/lib/python3.6/tarfile.py", line 2052, in extract
numeric_owner=numeric_owner)
File "/usr/lib/python3.6/tarfile.py", line 2122, in _extract_member
self.makefile(tarinfo, targetpath)
File "/usr/lib/python3.6/tarfile.py", line 2163, in makefile
with bltn_open(targetpath, "wb") as target:
IsADirectoryError: [Errno 21] Is a directory: 'output'
|