Skip to content

Instantly share code, notes, and snippets.

@pdarragh
Last active June 11, 2021 17:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pdarragh/56e2416f321973ccf228 to your computer and use it in GitHub Desktop.
Save pdarragh/56e2416f321973ccf228 to your computer and use it in GitHub Desktop.
Short PyObjC script to get a Mac's serial number without calling `system_profiler`.
#!/usr/bin/python
# (Note that we must use system Python on a Mac.)
####
# Quick script to get the computer's serial number.
#
# Written for @john.e.lamb on the MacAdmins Slack team.
import objc
import CoreFoundation
def import_iokit_functions_and_variables():
iokit = objc.initFrameworkWrapper(
"IOKit",
frameworkIdentifier="com.apple.framework.IOKit",
frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"),
globals=globals()
)
functions = [
("IOServiceGetMatchingService", b"II@"),
("IOServiceMatching", b"@or*", "", dict(
arguments=
{
0: dict(
type=objc._C_PTR + objc._C_CHAR_AS_TEXT,
c_array_delimited_by_null=True,
type_modifier=objc._C_IN)
}
)),
("IORegistryEntryCreateCFProperty", b"@I@@I")
]
variables = [
("kIOMasterPortDefault", b"I"),
("kIOPlatformSerialNumberKey", b"*")
]
objc.loadBundleFunctions(iokit, globals(), functions)
objc.loadBundleVariables(iokit, globals(), variables)
def get_serial():
import_iokit_functions_and_variables()
platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
serial = IORegistryEntryCreateCFProperty(platformExpert, CoreFoundation.CFSTR(kIOPlatformSerialNumberKey), CoreFoundation.kCFAllocatorDefault, 0)
return serial
if __name__ == '__main__':
serial = get_serial()
print("Serial: {}".format(serial))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment