Search code examples
pythonpython-3.xexearchive7zip

How to extract contents of exe-archive using python?


I haven an .exe installer, which can easily be opened with 7zip; and it's contents can be extracted without installing.

I'm using pre-compiled 7z.exe and python's subprocess to extract it.

import os, subprocess
subprocess.call(r'"7z.exe" x ' + "Installer.exe" + ' -o' + os.getcwd())

However now I'm looking for a method which will be pure code and doesn't depend on any external executable, to extract contents of packed exe.

I've tried libraries like tarfile, PyLZMA, py7zlib however they fail to extract the exe, or will complain that the file format is not valid, etc.


Solution

  • The self-extracting archive is just an executable with a 7zip archive on the end. You could look for all the possible starts of the archive and try decompressing the file handle starting there:

    HEADER = b'7z\xBC\xAF\x27\x1C'
    
    def try_decompressing_archive(filename):
        with open(filename, 'rb') as handle:
            start = 0
    
            # Try decompressing the archive at all the possible header locations
            while True:
                handle.seek(start)
    
                try:
                    return decompress_archive(handle)
                except SomeDecompressionException:
                    # We find the next instance of HEADER, skipping the current one
                    start += handle.read().index(HEADER, 1)