Created
February 3, 2025 19:26
-
-
Save colematt/ec8eb3436d14bc938a96a4d537d535d9 to your computer and use it in GitHub Desktop.
[Determine file type from magic numbers] #python3
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
#!/usr/bin/env python3 | |
import sys | |
import os.path | |
def isELF(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0x7F, 0x45, 0x4C, 0x46) | |
def isUniversalMachO(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0xCA, 0xFE, 0xBA, 0xBE) | |
def is32bMachO(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0xCE, 0xFA, 0xED, 0xFE) | |
def is64bMachO(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0xCF, 0xFA, 0xED, 0xFE) | |
def isMachO(path): | |
return isUniversalMachO(path) \ | |
or is32bMachO(path) \ | |
or is64bMachO(path) | |
def isPE(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(2)) == (0x5A, 0x4D) | |
def isRPM(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0xED, 0xAB, 0xEE, 0xDB) | |
def isDEB(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(8)) == (0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A) | |
def isGZ(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(2)) == (0x1F, 0x8B) | |
def isTAR(path): | |
with open(path, "rb") as fp: | |
fp.read(256) | |
magic = tuple(fp.read(8)) | |
return magic == ('u', 's', 't', 'a', 'r', 0, 0, 0) \ | |
or magic == ('u', 's', 't', 'a', 'r', 0x20, 0x20, 0) | |
def isZIP(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(4)) == (0x50, 0x4B, 0x03, 0x04) | |
def is7Z(path): | |
with open(path, "rb") as fp: | |
return tuple(fp.read(6)) == (0x37, 0x5A, 0xBC, 0xAF, 0x27, 0x1C) | |
tests = (isELF, isUniversalMachO, is32bMachO, is64bMachO, isPE, isRPM, isDEB, isGZ, isTAR, isZIP, is7Z) | |
if __name__ == "__main__": | |
if len(sys.argv) >= 2: | |
for arg in sys.argv[1:]: | |
if os.path.isfile(arg): | |
print(arg) | |
for test in tests: | |
print(str(test), test(arg)) | |
else: | |
print("usage: filesig path [path...]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment