From netheril96 at gmail.com Thu Mar 3 00:21:29 2022 From: netheril96 at gmail.com (Siyuan Ren) Date: Thu, 3 Mar 2022 13:21:29 +0800 Subject: [python-win32] What happens in a Python service in case of exception thrown? Message-ID: I'm trying to subclass win32serviceutil.ServiceFramework in order to create a Windows service in Python. I vaguely understand how each stage of service works, but I wonder, what happens if any of the python code throws an exception? Will the service stop, or put in an abnormal state without recourse? -------------- next part -------------- An HTML attachment was scrubbed... URL: From skippy.hammond at gmail.com Thu Mar 3 00:37:25 2022 From: skippy.hammond at gmail.com (Mark Hammond) Date: Thu, 3 Mar 2022 16:37:25 +1100 Subject: [python-win32] What happens in a Python service in case of exception thrown? In-Reply-To: References: Message-ID: On 3/03/2022 4:21 pm, Siyuan Ren wrote: > I'm trying to subclass?win32serviceutil.ServiceFramework in order to > create a Windows service in Python. I vaguely understand how each stage > of service works, but I wonder, what happens if any of the python code > throws an exception? Will the service?stop, or put in an abnormal state > without recourse? In general it will log a message to the eventlog and stop. Up until https://github.com/mhammond/pywin32/issues/1563 & https://github.com/mhammond/pywin32/pull/1566, it ended up reporting a normal `SERVICE_STOPPED` with an exit code of zero, but now it reports a non-zero code so you can configure it to auto-restart on exceptions. HTH, Mark From momchil at bojinov.info Mon Mar 7 17:08:03 2022 From: momchil at bojinov.info (momchil at bojinov.info) Date: Tue, 8 Mar 2022 00:08:03 +0200 Subject: [python-win32] zmq under win32service Message-ID: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> Hello, I m trying to serve 0mq listener under win32 service Code works fine while in interactive session Client: import zmq, json context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('ipc://cache/mm') socket.send_json(json.dumps({"2" : "1"})) message = socket.recv_json() print(message) server: import zmq, json context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('ipc://cache/mm') while True: message = socket.recv_json() print(message) socket.send_json(json.dumps({"data" : "BLA BLA"})) Once I start the service though I can't send/receive content Both service and cmd/client run under the same account (not SYSTEM) I was wondering if I can even use while True without the spawning a separate thread for it ? I m using the service code from: https://stackoverflow.com/questions/55677165/python-flask-as-windows-service (And the service skeleton win32_service.py) Help appreciated Momchil -------------- next part -------------- An HTML attachment was scrubbed... URL: From skippy.hammond at gmail.com Mon Mar 7 21:36:56 2022 From: skippy.hammond at gmail.com (Mark Hammond) Date: Tue, 8 Mar 2022 13:36:56 +1100 Subject: [python-win32] zmq under win32service In-Reply-To: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> References: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> Message-ID: <730a828a-a688-e1b9-59a8-e7eb5ccfc4c9@gmail.com> I've no clear idea what might be going wrong, but: * The `while True` should be fine - it obviously has limitations, but will work in the simple case. * You need some way of working out *what* is going wrong before you can work out *why*. It's possible the `print` statements are failing - I don't think the service framework does anything to ensure sys.stdout is valid. Most examples use `win32traceutil` to redirect sys.stdout, or you can use the event-log or anything else, but knowing exactly what is failing (ie, exactly how far it is getting) will be necessary to understand. Cheers, Mark On 8/03/2022 9:08 am, momchil at bojinov.info wrote: > Hello, > > I m trying to serve 0mq listener under win32 service > > Code works fine while in interactive session > > Client: > > import zmq, json > > context = zmq.Context() > > socket = context.socket(zmq.REQ) > > socket.connect('ipc://cache/mm') > > socket.send_json(json.dumps({"2" : "1"})) > > message = socket.recv_json() > > print(message) > > server: > > import zmq, json > > context = zmq.Context() > > socket = context.socket(zmq.REP) > > socket.bind('ipc://cache/mm') > > while True: > > ?????????????? message = socket.recv_json() > > ?????????????? print(message) > > ?????????????? socket.send_json(json.dumps({"data" : "BLA BLA"})) > > Once I start the service though I can?t send/receive content > > Both service and cmd/client run under the same account (not SYSTEM) > > I was wondering if I can even use while True without the spawning a > separate thread for it ? > > I m using the service code from: > > https://stackoverflow.com/questions/55677165/python-flask-as-windows-service > > (And the service skeleton /*win32_service.py*/) > > Help appreciated > > Momchil > > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 From momchil at bojinov.info Tue Mar 8 01:50:01 2022 From: momchil at bojinov.info (momchil at bojinov.info) Date: Tue, 8 Mar 2022 08:50:01 +0200 Subject: [python-win32] zmq under win32service In-Reply-To: <730a828a-a688-e1b9-59a8-e7eb5ccfc4c9@gmail.com> References: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> <730a828a-a688-e1b9-59a8-e7eb5ccfc4c9@gmail.com> Message-ID: <004801d832b8$bc31a110$3494e330$@bojinov.info> Hi, Thank you for responding I do have a logging class I use in my framework. I get a log entry right before the loop and nothing from inside Wherever I put 'print' in the sample consider 'log.info' Zmq is not raising much anyway and making this difficult. Now that I have not consumed rakia in 8 hours and having had a good night sleep - I switched the IPC with a TCP socket and it worked OK My question now is (realizing this is the wrong forum to ask) should this work with IPC ? One process being a user one and the other one being a service - both running under the same user Momchil -----Original Message----- From: Mark Hammond Sent: Tuesday, March 8, 2022 4:37 AM To: momchil at bojinov.info; python-win32 at python.org Subject: Re: [python-win32] zmq under win32service I've no clear idea what might be going wrong, but: * The `while True` should be fine - it obviously has limitations, but will work in the simple case. * You need some way of working out *what* is going wrong before you can work out *why*. It's possible the `print` statements are failing - I don't think the service framework does anything to ensure sys.stdout is valid. Most examples use `win32traceutil` to redirect sys.stdout, or you can use the event-log or anything else, but knowing exactly what is failing (ie, exactly how far it is getting) will be necessary to understand. Cheers, Mark On 8/03/2022 9:08 am, momchil at bojinov.info wrote: > Hello, > > I m trying to serve 0mq listener under win32 service > > Code works fine while in interactive session > > Client: > > import zmq, json > > context = zmq.Context() > > socket = context.socket(zmq.REQ) > > socket.connect('ipc://cache/mm') > > socket.send_json(json.dumps({"2" : "1"})) > > message = socket.recv_json() > > print(message) > > server: > > import zmq, json > > context = zmq.Context() > > socket = context.socket(zmq.REP) > > socket.bind('ipc://cache/mm') > > while True: > > message = socket.recv_json() > > print(message) > > socket.send_json(json.dumps({"data" : "BLA BLA"})) > > Once I start the service though I can?t send/receive content > > Both service and cmd/client run under the same account (not SYSTEM) > > I was wondering if I can even use while True without the spawning a > separate thread for it ? > > I m using the service code from: > > https://stackoverflow.com/questions/55677165/python-flask-as-windows-s > ervice > service> > > (And the service skeleton /*win32_service.py*/) > > Help appreciated > > Momchil > > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 From timr at probo.com Tue Mar 8 16:41:42 2022 From: timr at probo.com (Tim Roberts) Date: Tue, 8 Mar 2022 13:41:42 -0800 Subject: [python-win32] zmq under win32service In-Reply-To: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> References: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> Message-ID: momchil at bojinov.info wrote: > > server: > > import zmq, json > > context = zmq.Context() > > socket = context.socket(zmq.REP) > > socket.bind('ipc://cache/mm') > > while True: > > ?????????????? message = socket.recv_json() > > ?????????????? print(message) > > socket.send_json(json.dumps({"data" : "BLA BLA"})) > > Once I start the service though I can?t send/receive content > > Both service and cmd/client run under the same account (not SYSTEM) > Where is the service code? > I was wondering if I can even use while True without the spawning a > separate thread for it ? > No.? Just like a Windows GUI app, a Windows service has a main message loop that has to remain in control, so it can receive and dispatch messages from the service manager.? The system sends "are you awake?" messages periodically to make sure you're still alive.? If you aren't getting back to the main loop, then you will be terminated. So, if you're using the sample you mentioned, the service "def main(self):" will need to launch a thread to do your listening. You will also need to have your thread check the "stop_request" flag, so you can cleanly exit when the service is terminated. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3389 bytes Desc: S/MIME Cryptographic Signature URL: From skippy.hammond at gmail.com Wed Mar 9 00:00:05 2022 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 9 Mar 2022 16:00:05 +1100 Subject: [python-win32] zmq under win32service In-Reply-To: References: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> Message-ID: <8609487b-1bd4-c484-001a-22c50da7b2da@gmail.com> I admit I've never fully understood the threading model used to control services, and agree that almost every "real" service will create threads - but it's not clear to me that they *must* - eg, I've seen demo services that use a similar loop, and https://github.com/mhammond/pywin32/blob/main/win32/Demos/service/serviceEvents.py has: def SvcDoRun(self): # do nothing at all - just wait to be stopped win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) and seems to work. So I could understand if the symptoms reported here were along the lines of "windows thinks my service has hung and killed it" or something similar, but it's not clear to me that the lack of a worker thread is the reason the service can't make it a single time around that loop. Cheers, Mark On 9/03/2022 8:41 am, Tim Roberts wrote: > momchil at bojinov.info wrote: >> >> server: >> >> import zmq, json >> >> context = zmq.Context() >> >> socket = context.socket(zmq.REP) >> >> socket.bind('ipc://cache/mm') >> >> while True: >> >> ?????????????? message = socket.recv_json() >> >> ?????????????? print(message) >> >> socket.send_json(json.dumps({"data" : "BLA BLA"})) >> >> Once I start the service though I can?t send/receive content >> >> Both service and cmd/client run under the same account (not SYSTEM) >> > Where is the service code? > > >> I was wondering if I can even use while True without the spawning a >> separate thread for it ? >> > No.? Just like a Windows GUI app, a Windows service has a main message > loop that has to remain in control, so it can receive and dispatch > messages from the service manager.? The system sends "are you awake?" > messages periodically to make sure you're still alive.? If you aren't > getting back to the main loop, then you will be terminated. > > So, if you're using the sample you mentioned, the service "def > main(self):" will need to launch a thread to do your listening. You will > also need to have your thread check the "stop_request" flag, so you can > cleanly exit when the service is terminated. > > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 From momchil at bojinov.info Wed Mar 9 01:28:04 2022 From: momchil at bojinov.info (momchil at bojinov.info) Date: Wed, 9 Mar 2022 08:28:04 +0200 Subject: [python-win32] zmq under win32service In-Reply-To: <8609487b-1bd4-c484-001a-22c50da7b2da@gmail.com> References: <001301d8326f$d119fe90$734dfbb0$@bojinov.info> <8609487b-1bd4-c484-001a-22c50da7b2da@gmail.com> Message-ID: <00dc01d8337e$d54d04c0$7fe70e40$@bojinov.info> Morning guys, I m fairly certain it is not a problem with the win32service code as it works just fine with a tcp socket The actual service runs ok and is not stuck. It responds to stop command. I don't mind sharing the code: https://github.com/bozhinov/cache-poc I guess 0mq is not the way to go for me. I just need a piece of shared memory I can place structured data and access it from multiple processes. Why is that so hard to do under Windows ? No in-memory databases either and I m not using subsystem for linux Momchil -----Original Message----- From: python-win32 On Behalf Of Mark Hammond Sent: Wednesday, March 9, 2022 7:00 AM To: Tim Roberts ; python-win32 at python.org Subject: Re: [python-win32] zmq under win32service I admit I've never fully understood the threading model used to control services, and agree that almost every "real" service will create threads - but it's not clear to me that they *must* - eg, I've seen demo services that use a similar loop, and https://github.com/mhammond/pywin32/blob/main/win32/Demos/service/serviceEvents.py has: def SvcDoRun(self): # do nothing at all - just wait to be stopped win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) and seems to work. So I could understand if the symptoms reported here were along the lines of "windows thinks my service has hung and killed it" or something similar, but it's not clear to me that the lack of a worker thread is the reason the service can't make it a single time around that loop. Cheers, Mark On 9/03/2022 8:41 am, Tim Roberts wrote: > momchil at bojinov.info wrote: >> >> server: >> >> import zmq, json >> >> context = zmq.Context() >> >> socket = context.socket(zmq.REP) >> >> socket.bind('ipc://cache/mm') >> >> while True: >> >> message = socket.recv_json() >> >> print(message) >> >> socket.send_json(json.dumps({"data" : "BLA BLA"})) >> >> Once I start the service though I can?t send/receive content >> >> Both service and cmd/client run under the same account (not SYSTEM) >> > Where is the service code? > > >> I was wondering if I can even use while True without the spawning a >> separate thread for it ? >> > No. Just like a Windows GUI app, a Windows service has a main message > loop that has to remain in control, so it can receive and dispatch > messages from the service manager. The system sends "are you awake?" > messages periodically to make sure you're still alive. If you aren't > getting back to the main loop, then you will be terminated. > > So, if you're using the sample you mentioned, the service "def > main(self):" will need to launch a thread to do your listening. You > will also need to have your thread check the "stop_request" flag, so > you can cleanly exit when the service is terminated. > > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 _______________________________________________ python-win32 mailing list python-win32 at python.org https://mail.python.org/mailman/listinfo/python-win32 From hisabojp at gmail.com Wed Mar 9 05:20:12 2022 From: hisabojp at gmail.com (H.Fujii) Date: Wed, 9 Mar 2022 19:20:12 +0900 Subject: [python-win32] Unable to detect shutdown Message-ID: <47c1994b-450d-e77a-7dc3-5d5e92ab1351@gmail.com> I'm currently developing a console program in Python 3.9. I want to detect the shutdown of Windows and save the data to a file safely. I created a sample program by referring to the following URL. https://docs.microsoft.com/en-us/windows/console/registering-a-control-handler-function However, the sample program does not detect shutdown (CTRL_SHUTDOWN_EVENT) well. I have confirmed that CTRL_C_EVENT and CTRL_CLOSE_EVENT can be detected successfully. Please let me know how to detect a successful shutdown. Sincerely, Expected behavior and actual behavior. detecting the shutdown of Windows Steps to reproduce the problem. python mian.py Version of Python and pywin32 Python 3.8.11 pywin32 version 228 # Python Code : main.py import time import win32api import win32con def ctrl_handler(evt): with open('event_info.txt', 'a') as f: if evt == win32con.CTRL_C_EVENT: f.write("CTRL_C_EVENT\n") return True elif evt == win32con.CTRL_CLOSE_EVENT: f.write("CTRL_CLOSE_EVENT\n") return True elif evt == win32con.CTRL_BREAK_EVENT: f.write("CTRL_BREAK_EVENT\n") return False elif evt == win32con.CTRL_LOGOFF_EVENT: f.write("CTRL_LOGOFF_EVENT\n") return False elif evt == win32con.CTRL_SHUTDOWN_EVENT: f.write("CTRL_SHUTDOWN_EVENT\n") return False else: return False def main(): print('Starting Program!') win32api.SetConsoleCtrlHandler(ctrl_handler, True) while True: time.sleep(1) print('End of Program!') if __name__ == "__main__": main() From eryksun at gmail.com Wed Mar 9 17:28:34 2022 From: eryksun at gmail.com (Eryk Sun) Date: Wed, 9 Mar 2022 16:28:34 -0600 Subject: [python-win32] Unable to detect shutdown In-Reply-To: <47c1994b-450d-e77a-7dc3-5d5e92ab1351@gmail.com> References: <47c1994b-450d-e77a-7dc3-5d5e92ab1351@gmail.com> Message-ID: On 3/9/22, H.Fujii wrote: > I'm currently developing a console program in Python 3.9. > I want to detect the shutdown of Windows and save the data to a file > safely. > I created a sample program by referring to the following URL. > https://docs.microsoft.com/en-us/windows/console/registering-a-control-handler-function > > However, the sample program does not detect shutdown > (CTRL_SHUTDOWN_EVENT) well. Console control events are sent by the Windows session server, csrss.exe, by creating a thread in the target process that starts at CtrlRoutine() in kernelbase.dll. This includes the cancel (i.e. Ctrl+C), break, and close events that are requested by a console session host (i.e. conhost.exe or openconsole.exe), as well as the system-initiated logoff and shutdown events. The session server sends the logoff and shutdown events to any process that isn't a GUI process. It doesn't matter whether or not the process is attached to a console. For example, the service control manager in services.exe depends on the console shutdown event, even though it is not a console application and is not attached to a console. A GUI process is one that's connected to a window station (e.g. interactive "WinSta0"), with one or more threads connected to a desktop (e.g. "WinSta0\Default"). Loading user32.dll, directly or indirectly, connects the process and loading thread to a window station and desktop (e.g. as set by its STARTUPINFO). In order to avoid getting converted to a GUI process, a console or background application has to carefully restrict itself to the base API, avoiding anything that might end up loading user32.dll, or by spawning a child process to call anything that loads user32.dll as a remote procedure call. Python 3.9+ starts out okay in this regard. But some extension modules in the standard library -- e.g. _ssl.pyd, _hashlib.pyd, and _ctypes.pyd -- do not delay-load dependencies that end up loading user32.dll. Thus, for example, it is currently impossible to use ctypes to handle the console logoff and shutdown events. As to win32api, it directly depends on user32.dll as well as indirectly via other DLLs. I think partitioning out a win32base module would be a worthy goal, but that's up to the PyWin32 project developers. If you can't take the simple route of using console logoff and shutdown events, then all you can do is fully embrace being a GUI process. Create a hidden top-level window with a message loop that handles WM_QUERYENDSESSION [1] and WM_ENDSESSION [2]. --- [1] https://docs.microsoft.com/en-us/windows/win32/shutdown/wm-queryendsession [2] https://docs.microsoft.com/en-us/windows/win32/shutdown/wm-endsession From antoine.ferron at bitlogik.fr Wed Mar 9 17:02:54 2022 From: antoine.ferron at bitlogik.fr (Antoine FERRON) Date: Wed, 9 Mar 2022 23:02:54 +0100 Subject: [python-win32] Unable to detect shutdown In-Reply-To: <47c1994b-450d-e77a-7dc3-5d5e92ab1351@gmail.com> References: <47c1994b-450d-e77a-7dc3-5d5e92ab1351@gmail.com> Message-ID: <5A50A36F-1EF2-46AF-9852-E7DF0B4F639B@getmailspring.com> I would recommend that you work with an object from a class, and using def __del__(self): I think when Windows shutdown, it send a stop/quit signal to all processes. When your Python is stopped by the OS, it can stop gracefully, and write the info in the file to backup, before it dies. This could work whatever the interruption reason, whatever the OS. As this is called everytime the object is destructed/deleted. About the events to listen to, when the system shutdowns and sends a signal, you can read this (https://www.apriorit.com/dev-blog/413-win-api-shutdown-events). There's a note about the fact that they may not work correctly. This happens when the OS calls internal console cleanup routines before executing the process signal handler. One alternative also can be to create a fake window and catch WM_QUERYENDSESSION and/or WM_POWERBROADCAST events, so you turn your application into a GUI app for Windows point of view, and you rely on possibly more reliable events. Regards, _____________________________________ Antoine FERRON Pr?sident ? BitLogiK bitlogik.fr (https://bitlogik.fr) ? PGP Key ID#22F95B31 (https://keys.openpgp.org/search?q=antoine.ferron%40bitlogik.fr) On Mar 9 2022, at 11:20 am, H.Fujii wrote: > I'm currently developing a console program in Python 3.9. > I want to detect the shutdown of Windows and save the data to a file safely. > I created a sample program by referring to the following URL. > https://docs.microsoft.com/en-us/windows/console/registering-a-control-handler-function > > However, the sample program does not detect shutdown > (CTRL_SHUTDOWN_EVENT) well. > I have confirmed that CTRL_C_EVENT and CTRL_CLOSE_EVENT can be detected > successfully. > Please let me know how to detect a successful shutdown. > > Sincerely, > > Expected behavior and actual behavior. > detecting the shutdown of Windows > > Steps to reproduce the problem. > python mian.py > > Version of Python and pywin32 > Python 3.8.11 > pywin32 version 228 > > > # Python Code : main.py > import time > import win32api > import win32con > > def ctrl_handler(evt): > with open('event_info.txt', 'a') as f: > if evt == win32con.CTRL_C_EVENT: > f.write("CTRL_C_EVENT\n") > return True > elif evt == win32con.CTRL_CLOSE_EVENT: > f.write("CTRL_CLOSE_EVENT\n") > return True > elif evt == win32con.CTRL_BREAK_EVENT: > f.write("CTRL_BREAK_EVENT\n") > return False > elif evt == win32con.CTRL_LOGOFF_EVENT: > f.write("CTRL_LOGOFF_EVENT\n") > return False > elif evt == win32con.CTRL_SHUTDOWN_EVENT: > f.write("CTRL_SHUTDOWN_EVENT\n") > return False > else: > return False > > def main(): > print('Starting Program!') > win32api.SetConsoleCtrlHandler(ctrl_handler, True) > while True: > time.sleep(1) > print('End of Program!') > > if __name__ == "__main__": > main() > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmatthew at optonline.net Sat Mar 12 02:02:01 2022 From: cmatthew at optonline.net (Craig R. Matthews) Date: Sat, 12 Mar 2022 02:02:01 -0500 Subject: [python-win32] pywin32 question Message-ID: <05c60f13-fc88-b25c-e270-248b7103a049@optonline.net> I was wondering if there is a way in python to determine the idle time for a terminal server session as QUERY USER does. Also, is there a way to get that python code to run for a server other than the one running the code (as in QUERY USER /SERVER:name)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at manross.net Sun Mar 13 11:26:11 2022 From: steven at manross.net (Steven Manross) Date: Sun, 13 Mar 2022 15:26:11 +0000 Subject: [python-win32] pywin32 question In-Reply-To: <05c60f13-fc88-b25c-e270-248b7103a049@optonline.net> References: <05c60f13-fc88-b25c-e270-248b7103a049@optonline.net> Message-ID: While I don?t have a huge environment to test in, this seems to work remotely from my win 10 pc to my Windows Server 2016 which has remote admin RDP enabled? I would assume it?s the same APIs to talk to a full fledged WTS Server. Kudos to the internet for having the answer already written down for me? even if it was in python 2 syntax (what else should I expect from a post in 11/2007?). ? https://mail.python.org/pipermail/python-win32/2007-November/006425.html import win32ts for s in win32ts.WTSEnumerateSessions(win32ts.WTSOpenServer("MYSERVER.MYDOMAIN.COM"),1): if s['State'] == win32ts.WTSActive: print(f"Session is active: {s}") output: Session is active: {'SessionId': 1, 'WinStationName': 'RDP-Tcp#124', 'State': 0} take a look at win32ts here: http://timgolden.me.uk/pywin32-docs/win32ts.html I am guessing you would also want to use ?WTSQuerySessionInformation? as well to get more detailed information about the session, but I will leave that to you to explore. I just found this today, so I am no expert on use of this module but it looks GREAT and I will likely develop something with it myself eventually. Steven From: python-win32 On Behalf Of Craig R. Matthews Sent: Saturday, March 12, 2022 12:02 AM To: python-win32 at python.org Subject: [python-win32] pywin32 question I was wondering if there is a way in python to determine the idle time for a terminal server session as QUERY USER does. Also, is there a way to get that python code to run for a server other than the one running the code (as in QUERY USER /SERVER:name)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at manross.net Sun Mar 13 12:28:01 2022 From: steven at manross.net (Steven Manross) Date: Sun, 13 Mar 2022 16:28:01 +0000 Subject: [python-win32] pywin32 question In-Reply-To: References: <05c60f13-fc88-b25c-e270-248b7103a049@optonline.net> Message-ID: Ok.. fine? I was interested so I played with it more. Here?s what I came up with. Enjoy! import win32ts protocols = { win32ts.WTS_PROTOCOL_TYPE_CONSOLE: "Console", win32ts.WTS_PROTOCOL_TYPE_ICA: "Citrix", win32ts.WTS_PROTOCOL_TYPE_RDP: "RDP", } session_types = {win32ts.WTSConnected: "Connected", win32ts.WTSActive: "Active", win32ts.WTSConnectQuery: "Connect Pending", win32ts.WTSShadow: "Shadowing another session", win32ts.WTSDisconnected: "Disconnected", win32ts.WTSIdle: "Idle", win32ts.WTSListen: "Listening", win32ts.WTSReset: " Resetting", win32ts.WTSDown: "Down -- Error", win32ts.WTSInit: "Initializing"} server_name = "someserver.mydomain.com" ts_connection = win32ts.WTSOpenServer(server_name) for s in win32ts.WTSEnumerateSessions(ts_connection, 1): if s['WinStationName'] != "Services" and s['State'] != win32ts.WTSListen: user = win32ts.WTSQuerySessionInformation(ts_connection, s['SessionId'], win32ts.WTSUserName) if not user: user = "No one is logged in" protocol = win32ts.WTSQuerySessionInformation(ts_connection, s['SessionId'], win32ts.WTSClientProtocolType) print(f"Session: {s['SessionId']} - State = {session_types[s['State']]} --> User: {user} -- Protocol: {protocols[protocol]}") win32ts.WTSCloseServer(ts_connection) output: Session: 1 - State = Active --> User: myusername -- Protocol: RDP Session: 2 - State = Connected --> User: No one is logged in -- Protocol: Console HTH Steven From: python-win32 On Behalf Of Steven Manross Sent: Sunday, March 13, 2022 8:26 AM To: Craig R. Matthews ; python-win32 at python.org Subject: Re: [python-win32] pywin32 question While I don?t have a huge environment to test in, this seems to work remotely from my win 10 pc to my Windows Server 2016 which has remote admin RDP enabled? I would assume it?s the same APIs to talk to a full fledged WTS Server. Kudos to the internet for having the answer already written down for me? even if it was in python 2 syntax (what else should I expect from a post in 11/2007?). ? https://mail.python.org/pipermail/python-win32/2007-November/006425.html import win32ts for s in win32ts.WTSEnumerateSessions(win32ts.WTSOpenServer("MYSERVER.MYDOMAIN.COM"),1): if s['State'] == win32ts.WTSActive: print(f"Session is active: {s}") output: Session is active: {'SessionId': 1, 'WinStationName': 'RDP-Tcp#124', 'State': 0} take a look at win32ts here: http://timgolden.me.uk/pywin32-docs/win32ts.html I am guessing you would also want to use ?WTSQuerySessionInformation? as well to get more detailed information about the session, but I will leave that to you to explore. I just found this today, so I am no expert on use of this module but it looks GREAT and I will likely develop something with it myself eventually. Steven From: python-win32 > On Behalf Of Craig R. Matthews Sent: Saturday, March 12, 2022 12:02 AM To: python-win32 at python.org Subject: [python-win32] pywin32 question I was wondering if there is a way in python to determine the idle time for a terminal server session as QUERY USER does. Also, is there a way to get that python code to run for a server other than the one running the code (as in QUERY USER /SERVER:name)? -------------- next part -------------- An HTML attachment was scrubbed... URL: