win32ts_logoff_disconnected.py 950 B

123456789101112131415161718192021
  1. """ Finds any disconnected terminal service sessions and logs them off"""
  2. import win32ts
  3. import pywintypes
  4. import winerror
  5. sessions=win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE)
  6. for session in sessions:
  7. """
  8. WTS_CONNECTSTATE_CLASS: WTSActive,WTSConnected,WTSConnectQuery,WTSShadow,WTSDisconnected,
  9. WTSIdle,WTSListen,WTSReset,WTSDown,WTSInit
  10. """
  11. if session['State']==win32ts.WTSDisconnected:
  12. sessionid=session['SessionId']
  13. username=win32ts.WTSQuerySessionInformation(win32ts.WTS_CURRENT_SERVER_HANDLE, sessionid, win32ts.WTSUserName)
  14. print('Logging off disconnected user:',username)
  15. try:
  16. win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, sessionid, True)
  17. except pywintypes.error as e:
  18. if e.winerror == winerror.ERROR_ACCESS_DENIED:
  19. print("Can't kill that session:", e.strerror)
  20. else:
  21. raise