如何使用 python 提取 exe-archive 的内容?
How to extract contents of exe-archive using python?
我有一个.exe安装程序,可以很容易地用7zip打开;无需安装即可提取其内容。
我正在使用预编译的 7z.exe 和 python 的 subprocess
来提取它。
import os, subprocess
subprocess.call(r'"7z.exe" x ' + "Installer.exe" + ' -o' + os.getcwd())
但是现在我正在寻找一种方法,它将是纯代码并且不依赖于任何外部可执行文件,以提取打包的 exe 的内容。
我试过 tarfile, PyLZMA, py7zlib
这样的库,但是它们无法提取 exe,或者会抱怨文件格式无效等。
自解压文件只是一个结尾带有 7zip 文件的可执行文件。您可以查找存档的所有可能开头并尝试从那里开始解压缩文件句柄:
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)
我有一个.exe安装程序,可以很容易地用7zip打开;无需安装即可提取其内容。
我正在使用预编译的 7z.exe 和 python 的 subprocess
来提取它。
import os, subprocess
subprocess.call(r'"7z.exe" x ' + "Installer.exe" + ' -o' + os.getcwd())
但是现在我正在寻找一种方法,它将是纯代码并且不依赖于任何外部可执行文件,以提取打包的 exe 的内容。
我试过 tarfile, PyLZMA, py7zlib
这样的库,但是它们无法提取 exe,或者会抱怨文件格式无效等。
自解压文件只是一个结尾带有 7zip 文件的可执行文件。您可以查找存档的所有可能开头并尝试从那里开始解压缩文件句柄:
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)