Skip to content

Instantly share code, notes, and snippets.

@pudquick
Last active October 12, 2022 20:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pudquick/581a71425439f2cf8f09 to your computer and use it in GitHub Desktop.
Save pudquick/581a71425439f2cf8f09 to your computer and use it in GitHub Desktop.
Calling sysctl from python via ctypes
from ctypes import CDLL, c_uint, byref, create_string_buffer
from ctypes.util import find_library
libc = CDLL(find_library("c"))
def sysctl(name, isString=True):
size = c_uint(0)
# Find out how big our buffer will be
libc.sysctlbyname(name, None, byref(size), None, 0)
# Make the buffer
buf = create_string_buffer(size.value)
# Re-run, but provide the buffer
libc.sysctlbyname(name, buf, byref(size), None, 0)
if isString:
return buf.value
else:
return buf.raw
@mlazovjp
Copy link

mlazovjp commented Sep 15, 2022

I am attempting to use this on a MacBook Pro 13-inch, M1, 2020 running macOS Monterey 12.5. I am using Python 3.10.5 downloaded from the official Python.org site.

I am trying to capture the equivalent of running "sysctl hw.model" from Terminal. When I run that in Terminal, I get:
hw.model: MacBookPro17,1

When I use your code and execute:
temp_model_sku = sysctl("hw.model")
print(F"temp_model_sku: {temp_model_sku}")

The output is:
temp_model_sku: b''

When I use the debugger to inspect the sysctl() code, pausing at
if isString:
the value of size is always 0.

Am I doing something wrong?

@Kentzo
Copy link

Kentzo commented Oct 5, 2022

@mlazovjp Try adding the b prefix to the option names, e.g. b"hw.model"

@mlazovjp
Copy link

@mlazovjp Try adding the b prefix to the option names, e.g. b"hw.model"

Kentzo,

Thanks for the assist. I figured it was something I was overlooking. I can confirm that this works properly now after making that change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment