Skip to content

Instantly share code, notes, and snippets.

@pudquick
Forked from pdarragh/get_serial.py
Created September 5, 2018 23:48
Show Gist options
  • Save pudquick/3839ebe8b1ec72a5e975ee92b3e34389 to your computer and use it in GitHub Desktop.
Save pudquick/3839ebe8b1ec72a5e975ee92b3e34389 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