modules def untar(archive)tar none trytar tarfile open(archivefor member in tar getmembers()if member name startswith(untrusted_prefixes)print("untrusted prefixignoring"member nameelif in member nameprint("suspect pathignoring"member nameelsetar extract(memberprint("unpacked"member nameexcept (tarfile tarerrorenvironmenterroras errerror(errfinallyif tar is not nonetar close(each file in tarball is called member the tarfile getmembers(function returns list of tarfile tarinfo objectsone for each member the member' filenameincluding its pathis in the tarfile tarinfo name attribute if the name begins with an untrusted prefixor contains in its pathwe output an error messageotherwisewe call tarfile extract(to save the member to disk the tarfile module has its own set of custom exceptionsbut we have taken the simplistic approach that if any exception occurs we output the error message and finish def error(messageexit_status= )print(messagesys exit(exit_statuswe have just quoted the error(function for completeness the (unquotedmain(function prints usage message if - or --help is givenotherwiseit performs some basic checks before calling untar(with the tarball' filename filedirectoryand process handling |the shutil module provides high-level functions for file and directory handlingincluding shutil copy(and shutil copytree(for copying files and entire directory treesshutil move(for moving directory treesand shutil rmtree(for removing entire directory treesincluding nonempty ones temporary files and directories should be created using the tempfile module which provides the necessary functionsfor exampletempfile mkstemp()and creates the temporaries in the most secure manner possible