首页 > 解决方案 > 如何检查文件是否是来自 Python 的 macOS 可执行文件?

问题描述

例如,给定:

$ cd /Applications/Xcode.app/Contents/MacOS
$ file Xcode
Xcode: Mach-O 64-bit executable x86_64

和:

$ cd /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A
$ file IDEKit
IDEKit: Mach-O 64-bit dynamically linked shared library x86_64

我希望能够做file正在做的事情,特别是检查文件是否是可执行文件,但以编程方式来自 Python。

我知道我可以调用file命令并解析 Python 的结果,但是有没有更好的方法不涉及调用file

注意:

$ ls -l IDEKit
-rwxr-xr-x 1 root wheel 17256912 Apr  5 17:42 IDEKit*

和:

$ ls -l Xcode
-rwxr-xr-x  1 root  wheel  44416 Apr 11 13:40 Xcode*

即,就文件系统权限位而言,它们都是“可执行的”,但只是Xcode真正的可执行文件。

标签: pythonmacos

解决方案


事实证明,macholib允许您从 Python 读取和检查文件的 Mach-O 标头(如果有的话)。所以代码如下:

def read_macho_headers( file ):
    try:
        return MachO.MachO( file ).headers
    except Exception:                   # not a Mach-O file
        return None

def is_macho_exe( macho_headers ):
    filetype = macho_headers[0].header.filetype
    return filetype == mach_o.MH_EXECUTE

将工作。


推荐阅读