Skip to content

Instantly share code, notes, and snippets.

@wolfhechel
Created July 7, 2016 10:14
Show Gist options
  • Save wolfhechel/11ccde089662a2f824c204a11f5f8032 to your computer and use it in GitHub Desktop.
Save wolfhechel/11ccde089662a2f824c204a11f5f8032 to your computer and use it in GitHub Desktop.
ctypes implementation to retrieve platform UUID on OS X
from ctypes import *
from ctypes import util
from platform import mac_ver
import uuid
iokit = cdll.LoadLibrary(util.find_library('IOKit'))
cf = cdll.LoadLibrary(util.find_library('CoreFoundation'))
cf.CFStringCreateWithCString.argtypes = [c_void_p, c_char_p, c_int32]
cf.CFStringCreateWithCString.restype = c_void_p
cf.CFStringGetCStringPtr.argtypes = [c_void_p, c_uint32]
cf.CFStringGetCStringPtr.restype = c_char_p
kCFAllocatorDefault = c_void_p.in_dll(cf, "kCFAllocatorDefault")
kCFStringEncodingMacRoman = 0
kIOMasterPortDefault = c_void_p.in_dll(iokit, "kIOMasterPortDefault")
kIOPlatformUUIDKey = "IOPlatformUUID".encode("mac_roman")
iokit.IOServiceMatching.restype = c_void_p
iokit.IOServiceGetMatchingService.argtypes = [c_void_p, c_void_p]
iokit.IOServiceGetMatchingService.restype = c_void_p
iokit.IORegistryEntryCreateCFProperty.argtypes = [c_void_p, c_void_p, c_void_p, c_uint32]
iokit.IORegistryEntryCreateCFProperty.restype = c_void_p
iokit.IOObjectRelease.argtypes = [c_void_p]
def get_platform_uuid_key():
""" Tries to retrieve the the platform UUID key using IOKit.framework IORegistry calls.
:return: uuid platform UUID if one could be retrieved, else None
"""
uuid_string = None
platform_expert = iokit.IOServiceGetMatchingService(
kIOMasterPortDefault,
iokit.IOServiceMatching(b"IOPlatformExpertDevice")
)
if platform_expert:
key = cf.CFStringCreateWithCString(kCFAllocatorDefault, kIOPlatformUUIDKey, kCFStringEncodingMacRoman)
serial_number_cfstring = iokit.IORegistryEntryCreateCFProperty(platform_expert, key, kCFAllocatorDefault, 0)
if serial_number_cfstring:
uuid_string = cf.CFStringGetCStringPtr(serial_number_cfstring, 0)
iokit.IOObjectRelease(platform_expert)
return uuid.UUID(uuid_string.decode()) if uuid_string else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment