Detect executable format using Python

In this article, I am sharing with you a small Python script that lets you detect if a file is an executable file and what platform the executable is targeting.

The following formats for 32 bits and 64bits processors are supported:

  • Mach-O files: both regular and universal formats
  • Windows PE files
  • Linux ELF files

The script

#---------------------------------------------------------------------
EXEFLAG_NONE        = 0x0000
EXEFLAG_LINUX       = 0x0001
EXEFLAG_WINDOWS     = 0x0002
EXEFLAG_MACOS       = 0x0004
EXEFLAG_MACOS_FAT   = 0x0008
EXEFLAG_32BITS      = 0x0010
EXEFLAG_64BITS      = 0x0020

# Keep signatures sorted by size
_EXE_SIGNATURES = (
    ("\x4D\x5A", EXEFLAG_WINDOWS),
    ("\xCE\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_32BITS),
    ("\xCF\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_64BITS),
    ("\xBE\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_32BITS | EXEFLAG_MACOS_FAT),
    ("\xBF\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_64BITS | EXEFLAG_MACOS_FAT),
    ("\x7F\x45\x4C\x46\x01", EXEFLAG_LINUX | EXEFLAG_32BITS),
    ("\x7F\x45\x4C\x46\x02", EXEFLAG_LINUX | EXEFLAG_64BITS)
)

def get_exeflags(filepath):
    try:
        with open(filepath, "rb") as f:
            buf = ""
            buf_len = 0
            for sig, flags in _EXE_SIGNATURES:
                sig_len = len(sig)
                if buf_len < sig_len:
                    buf += f.read(sig_len - buf_len)
                    buf_len = sig_len

                if buf == sig:
                    return flags
    except:
        pass

    return EXEFLAG_NONE

flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the right book for you.

Available in print or e-book editions from Amazon.
flower separator

Script explanation

  1. Build a signature table: for each executable file format, define the signatures and the corresponding flags. Note that the table is sorted by the smallest signature length to the longest
  2. Open the file and iterate in the signatures table
  3. Once a signature is found, return the flags associated by the signature

You might also like:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.