Last active
December 3, 2024 08:57
-
-
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`.
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/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