Last active
April 16, 2021 12:09
-
-
Save gregneagle/9bcf75c9f03d479a701da6191dd19062 to your computer and use it in GitHub Desktop.
Based on sysctl function by Michael Lynn aka frogor aka pudquick aka ????
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
# Based on sysctl function by Michael Lynn | |
# https://gist.github.com/pudquick/581a71425439f2cf8f09 | |
from ctypes import CDLL, c_uint, byref, create_string_buffer | |
from ctypes import cast, POINTER, c_int32, c_int64 | |
from ctypes.util import find_library | |
import struct | |
libc = CDLL(find_library('c')) | |
def sysctl(name, output_type=str): | |
'''Wrapper for sysctl so we don't have to use subprocess''' | |
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 output_type in (str, 'str'): | |
return buf.value | |
if output_type in (int, 'int'): | |
# complex stuff to cast the buffer contents to a Python int | |
if size.value == 4: | |
return cast(buf, POINTER(c_int32)).contents.value | |
if size.value == 8: | |
return cast(buf, POINTER(c_int64)).contents.value | |
if output_type == 'timeval': | |
if size.value == 16: | |
seconds, microseconds = struct.unpack('LL', buf.raw) | |
return {'seconds': seconds, 'microseconds': microseconds} | |
if output_type == 'raw': | |
# just return the raw buffer | |
return buf.raw | |
print sysctl('hw.cpufrequency', output_type=int) | |
print sysctl('hw.optional.x86_64', output_type=int) | |
print sysctl('hw.model') | |
print sysctl('kern.hostname') | |
print sysctl('kern.version') | |
print sysctl('machdep.cpu.vendor') | |
print sysctl('kern.boottime', output_type='timeval') | |
print repr(sysctl('hw.cacheconfig', output_type='raw')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment