已解决:如何在Python中使用ctypes获取Windows的会话ID?

问题描述 投票:0回答:1

我正在尝试使用 Python 中的 ctypes 检索 Windows 上当前用户会话的会话 ID。我的目标是在不依赖外部库的情况下实现这一目标。

这是我到目前为止的代码:

import ctypes
from ctypes import wintypes

def get_current_session_id():
    WTS_CURRENT_SERVER_HANDLE = ctypes.wintypes.HANDLE(-1)
    WTS_CURRENT_SESSION = 0xFFFFFFFF
    session_id = ctypes.create_string_buffer(4)  # Assuming a DWORD is 4 bytes

    server_handle = ctypes.windll.wtsapi32.WTSOpenServerW(None)

    if not server_handle:
        raise OSError("Failed to open server handle")

    try:
        result = ctypes.windll.wtsapi32.WTSQuerySessionInformationW(
            server_handle,
            WTS_CURRENT_SESSION,
            0,
            ctypes.byref(session_id),
            ctypes.byref(ctypes.c_ulong())
        )

        if not result:
            raise OSError("Failed to query session information")
    finally:
        ctypes.windll.wtsapi32.WTSCloseServer(server_handle)

    session_id_value = struct.unpack("I", session_id.raw)[0]
    return session_id_value

try:
    session_id = get_current_session_id()
    print("Current session ID:", session_id)
except OSError as e:
    print(f"Error: {e}")

但是,我遇到了访问冲突错误(例外:访问冲突读取)。我怀疑内存访问或 ctypes 的使用可能存在问题。

有人可以帮助我识别并纠正代码中的问题吗?此外,如果有其他方法可以使用 ctypes 实现相同的结果,我将不胜感激任何指导。

如果您能了解可能导致访问冲突错误的原因以及纠正代码的任何建议,我将不胜感激。

我尝试过的: 我尝试使用提供的利用 ctypes 的 Python 脚本检索 Windows 上当前用户会话的会话 ID。

我的期望: 我希望脚本能够成功检索会话 ID,而不会遇到任何错误,并提供正确的会话 ID 作为输出。

实际结果: 然而,在执行过程中,发生了访问冲突错误(异常:访问冲突读取)。

python windows winapi ctypes sessionid
1个回答
0
投票

问题已解决:

import ctypes
from ctypes import wintypes

def get_current_session_id():
    ProcessIdToSessionId = ctypes.windll.kernel32.ProcessIdToSessionId
    ProcessIdToSessionId.argtypes = [wintypes.DWORD, wintypes.PDWORD]
    ProcessIdToSessionId.restype = wintypes.BOOL

    process_id = wintypes.DWORD(ctypes.windll.kernel32.GetCurrentProcessId())
    session_id = wintypes.DWORD()

    if ProcessIdToSessionId(process_id, ctypes.byref(session_id)):
        return session_id.value
    else:
        raise ctypes.WinError()

current_session_id = get_current_session_id()
print(f"Current session ID: {current_session_id}")
© www.soinside.com 2019 - 2024. All rights reserved.