我正在尝试创建一个 Windows 服务(通过 Python 脚本),每次用户锁定和解锁工作站时都会进行记录。
当我使用 python WinLockUnlock.py debug
在 Debug模式下运行服务时,服务按预期工作。
但是如果我使用 python WinLockUnlock.py start
启动服务,result
变量 (SwitchDesktop(hDesktop)
) 始终为 0。问题仅在于 user32 函数,该服务写入日志文件没有任何问题。
那么,为什么user32的函数只能在 Debug模式下工作呢?
(我已经尝试使用管理员帐户运行该服务,但没有成功)
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()
最佳答案
我添加了错误检查并注意到拒绝访问
错误。仅当我尝试使用 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 服务即可拥有相同的功能
关于python - user32.SwitchDesktop 仅在 Debug模式下工作 - Python Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53642294/