Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.