user32.SwitchDesktop 仅适用于调试模式 - Python Windows 服务

user32.SwitchDesktop only works in debug mode - Python Windows service

我正在尝试创建一个 Windows 服务(来自 Python 脚本),该服务会在用户每次锁定和解锁工作站时进行记录。

当我 运行 服务处于调试模式时 python WinLockUnlock.py debug 服务按预期工作。

但如果我用 python WinLockUnlock.py start 启动服务,result 变量 (SwitchDesktop(hDesktop)) 始终为 0。问题仅出在 user32 函数上,服务写入日志文件没有任何问题。

那么,为什么user32的功能只能在调试模式下使用?

(我已经尝试 运行 使用管理员帐户连接该服务,但没有成功)

WinLockUnlock.py中的代码:

import time
from ctypes import WinDLL
from SMWinService import SMWinService


class WinLockUnlock(SMWinService):
    _svc_name_ = 'LockUnlock'
    _svc_display_name_ = 'Lock Unlock Script'
    _svc_description_ = 'Script que registra cuando se bloquea/desbloquea la sesión del usuario'

    def start(self):
        self.isrunning = True
        self.session_status = True
        self.writemsg('Service started')

    def stop(self):
        self.isrunning = False
        self.writemsg('Service stopped')

    def main(self):
        user32 = WinDLL('user32', use_last_error=True)
        OpenDesktop = user32.OpenDesktopW
        SwitchDesktop = user32.SwitchDesktop
        DESKTOP_SWITCHDESKTOP = 0x0100
        while self.isrunning:
            hDesktop = OpenDesktop('default', 0, False, DESKTOP_SWITCHDESKTOP)
            result = SwitchDesktop(hDesktop)
            self.writemsg('Test Result: {0}'.format(result))
            if result:
                if self.session_status == False:
                    self.session_status = True
                    self.writemsg('----------UNLOCKED----------')
            else:
                if self.session_status == True:
                    self.session_status = False
                    self.writemsg('----------LOCKED----------')
            time.sleep(2)

    def writemsg(self, msg):
        _date = time.strftime('%Y-%m-%d')
        _time = time.strftime('%H:%M:%S')
        filename = 'D:/Temp/TestPython/pyserv{0}.txt'.format(_date)
        with open(filename, 'a', newline='', encoding='utf-8') as file:
            file.write('{0} {1}: {2}\r\n'.format(_date, _time, msg))


if __name__ == '__main__':
    WinLockUnlock.parse_command_line()

我添加了错误检查并注意到 Access denied 错误。仅当我尝试使用 DESKTOP_SWITCHDESKTOP 权限 OpenDesktop 时才发生错误。 Turns out 服务无法与用户桌面交互:

... Services now run their own session with their own workstation and desktop ... Getting access to the user desktop is no longer possible. It is a security feature, it prevents shatter attacks.

所以我将我的脚本变成了一个 Windows 应用程序 Pyinstaller 并在启动文件夹中添加了快捷方式,现在我有相同的功能而不使用 Windows 服务