Created
August 28, 2016 16:13
-
-
Save sevas/06255545cf741b47b10e886a55a382df to your computer and use it in GitHub Desktop.
Detect whether a Windows exe or dll is a 32 or 64bit executable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Detect whether a Windows exe or dll is a 32 or 64bit executable. | |
Port of the perl script given by Paul Dixon on a Stack Overflow answer [1]_ | |
.. [1] http://stackoverflow.com/a/495305/40056 | |
""" | |
import sys | |
import os | |
from struct import unpack | |
def detect_petype(fpath): | |
with open(fpath, 'rb') as f: | |
dos_header = f.read(64) | |
magic, _, offset = unpack('2s58sl', dos_header) | |
if magic.decode('ascii') != 'MZ': | |
raise ValueError("The file {} is not an executable".format(fpath)) | |
f.seek(offset) | |
pe_header = f.read(6) | |
sig, _, machine = unpack('2s2sH', pe_header) | |
if sig.decode('ascii') != 'PE': | |
raise ValueError("The file {} is not a PE executable ".format(fpath)) | |
if machine == 0x014c: | |
return 'i386' | |
elif machine == 0x0200: | |
return 'IA64' | |
elif machine == 0x8664: | |
return 'AMD64' | |
else: | |
return 'unknown machine type: {}'.format(machine) | |
def main(): | |
if len(sys.argv) != 2: | |
print("usage: petype.py path/to/exefile") | |
return 1 | |
fpath = sys.argv[1] | |
if os.path.exists(fpath): | |
try: | |
print(detect_petype(fpath)) | |
return 0 | |
except (ValueError, IOError) as e: | |
print("Failure during parsing of the exe header. Reason:".format(e.args)) | |
return 1 | |
else: | |
return 1 | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment