Checking if an executable is 32-bit or 64-bit with a python3 script on Windows/Linux

半城伤御伤魂 提交于 2020-06-17 02:03:30

问题


I'm writing software in Python3 (more specifically: Python 3.8.1). At some point, the software needs to check if some arbitrary executable is 64-bit or 32-bit. After some research, I found the following post:

Checking if an exe is 32 bit or 64 bit

In this post, the following solution is offered:

subprocess.call(['dumpbin', '/HEADERS', 'test2.exe', '|', 'find', '"machine"'])

Unfortunately, this doesn't work in Python 3.8.1. That post is almost 8 years old and dates back to the Python 2.x days.

How can I test for 64-bitness from within Python 3.x? I need a solution for both Linux and Windows 10.

EDITS :
Windows-related note:
Apparently the DumpBin solution (see Checking if an exe is 32 bit or 64 bit post) requires Visual Studio to be installed. That's a no-no for me. My Python3 software should run on any Windows 10 computer.

Linux-related note:
On Linux, I don't neet to test PE format executables. Just Linux executables are fine.


回答1:


Detecting the 64-bitness of ELF binaries (i.e. Linux) is easy, because it's always at the same place in the header:

def is_64bit_elf(filename):
    with open(filename, "rb") as f:
        return f.read(5)[-1] == 2

I don't have a Windows system, so I can't test this, but this might work on Windows:

def is_64bit_pe(filename):
    import win32file
    return win32file.GetBinaryType(filename) == 6


来源:https://stackoverflow.com/questions/61999530/checking-if-an-executable-is-32-bit-or-64-bit-with-a-python3-script-on-windows-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!