Skip to content

Instantly share code, notes, and snippets.

@JnyJny
Created September 24, 2019 16:00
Show Gist options
  • Save JnyJny/5e5db87b70917b859d56515149b74ef0 to your computer and use it in GitHub Desktop.
Save JnyJny/5e5db87b70917b859d56515149b74ef0 to your computer and use it in GitHub Desktop.
Python Uptime on Mac for the Masochistic
#!/usr/bin/env python3
import ctypes
import ctypes.util
from datetime import datetime
libc_path = ctypes.util.find_library("libc")
libc = ctypes.cdll.LoadLibrary(libc_path)
USER_SIZE = 256
LINE_SIZE = 32
ID_SIZE = 4
HOST_SIZE = 256
BOOT_TIME = 2
class UTMPX_Entry(ctypes.Structure):
_fields_ = [
("ut_user", ctypes.c_char * USER_SIZE),
("ut_id", ctypes.c_char * ID_SIZE),
("ut_line", ctypes.c_char * LINE_SIZE),
("ut_pid", ctypes.c_int),
("ut_type", ctypes.c_short),
("ut_tv_secs", ctypes.c_long),
("ut_tv_usec", ctypes.c_int),
("ut_host", ctypes.c_char * HOST_SIZE),
]
getutxent = libc.getutxent
getutxent.restype = ctypes.POINTER(UTMPX_Entry)
def boot_epoch_time():
while True:
entry = getutxent()
if not entry:
break
if entry.contents.ut_type == BOOT_TIME:
return entry.contents.ut_tv_secs
return 0
if __name__ == "__main__":
boot_time = datetime.fromtimestamp(boot_epoch_time())
delta = datetime.now() - boot_time
print(f"boot @ {boot_time}")
print(f"delta: {delta}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment