def cmd_logout(self, cmd, args): targets = {} def_server = None for arg in args: arg = arg.upper() if arg.startswith("\\\\"): def_server = arg[2:] continue elif "@" in arg: sids, server = arg.split("@", 1) else: sids, server = arg, def_server sids = map(int, sids.split(",")) if server in targets: targets[server] += sids else: targets[server] = sids for server in targets: server_h = OpenServer(server) for sid in targets[server]: print("Logoff %s on %s" % (sid, server)) Ts.WTSLogoffSession(server_h, sid, False) CloseServer(server_h)
def logoff(self): sessionId = GetActiveSessionId() if sessionId != 0xffffffff: logging.debug("Logging off current user (session %d)", sessionId) win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, sessionId, 0) else: logging.debug("No active session. Ignoring log off command.")
def logoff(session_id): try: Logger.debug("perform_logoff: start logoff %d"%(session_id)) ret = win32ts.WTSLogoffSession(None, session_id, True) Logger.debug("perform_logoff: finish logoff %d ret: %s"%(session_id, str(ret))) except Exception, e: Logger.warn("perform_logoff: exception %s"%(e)) return False
def logoff_session(session_id): ''' Initiate the logoff of a session. :param session_id: The numeric Id of the session. :return: A boolean representing whether the logoff succeeded. CLI Example: .. code-block:: bash salt '*' rdp.logoff_session session_id salt '*' rdp.logoff_session 99 ''' try: win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True) except PyWinError as error: _LOG.error('Error calling WTSLogoffSession: %s', error) return False return True
def log_out_user(user_name=None): if user_name is None: user_name = util.get_param(2, None) if user_name is None: p("}}rn No User name provided - not logging out!}}xx") return False # Get list of current sessions sessions = win32ts.WTSEnumerateSessions(None, 1, 0) logged_off = False for session in sessions: active_session = session['SessionId'] station_name = session["WinStationName"] # Get the user for this session logged_in_user_name = win32ts.WTSQuerySessionInformation( None, active_session, win32ts.WTSUserName) #p("}}ynComparing: " + str(user_name) + "/" + logged_in_user_name) if user_name == logged_in_user_name: # Log this one out p("}}gnLogging off " + str(user_name) + " - typically takes 10-120 seconds...}}xx", debug_level=4) win32ts.WTSLogoffSession(None, active_session, True) logged_off = True if logged_off is not True: p("}}ybUser not logged in - skipping log off! " + str(user_name) + "}}xx", debug_level=5) else: p("}}gnUser logged out! " + str(user_name) + "}}xx", debug_level=3) return True
def delete(name, purge=False, force=False): ''' Remove a user from the minion Args: name (str): The name of the user to delete purge (bool, optional): Boolean value indicating that the user profile should also be removed when the user account is deleted. If set to True the profile will be removed. Default is False. force (bool, optional): Boolean value indicating that the user account should be deleted even if the user is logged in. True will log the user out and delete user. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' user.delete name ''' if six.PY2: name = _to_unicode(name) # Check if the user exists try: user_info = win32net.NetUserGetInfo(None, name, 4) except win32net.error as exc: log.error('User not found: {0}'.format(name)) log.error('nbr: {0}'.format(exc.winerror)) log.error('ctx: {0}'.format(exc.funcname)) log.error('msg: {0}'.format(exc.strerror)) return False # Check if the user is logged in # Return a list of logged in users try: sess_list = win32ts.WTSEnumerateSessions() except win32ts.error as exc: log.error('No logged in users found') log.error('nbr: {0}'.format(exc.winerror)) log.error('ctx: {0}'.format(exc.funcname)) log.error('msg: {0}'.format(exc.strerror)) # Is the user one that is logged in logged_in = False session_id = None for sess in sess_list: if win32ts.WTSQuerySessionInformation(None, sess['SessionId'], win32ts.WTSUserName) == name: session_id = sess['SessionId'] logged_in = True # If logged in and set to force, log the user out and continue # If logged in and not set to force, return false if logged_in: if force: try: win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True) except win32ts.error as exc: log.error('User not found: {0}'.format(name)) log.error('nbr: {0}'.format(exc.winerror)) log.error('ctx: {0}'.format(exc.funcname)) log.error('msg: {0}'.format(exc.strerror)) return False else: log.error('User {0} is currently logged in.'.format(name)) return False # Remove the User Profile directory if purge: try: sid = getUserSid(name) win32profile.DeleteProfile(sid) except pywintypes.error as exc: (number, context, message) = exc if number == 2: # Profile Folder Not Found pass else: log.error('Failed to remove profile for {0}'.format(name)) log.error('nbr: {0}'.format(exc.winerror)) log.error('ctx: {0}'.format(exc.funcname)) log.error('msg: {0}'.format(exc.strerror)) return False # And finally remove the user account try: win32net.NetUserDel(None, name) except win32net.error as exc: (number, context, message) = exc log.error('Failed to delete user {0}'.format(name)) log.error('nbr: {0}'.format(exc.winerror)) log.error('ctx: {0}'.format(exc.funcname)) log.error('msg: {0}'.format(exc.strerror)) return False return True
def logoff(session_id): """log off a particular session.""" if session_id < 0: raise ValueError('session ID must be non-negative') server = WTSServer(socket.gethostname()) win32ts.WTSLogoffSession(server.handle, session_id, True)
""" Finds any disconnected terminal service sessions and logs them off""" import win32ts import pywintypes import winerror sessions = win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE) for session in sessions: """ WTS_CONNECTSTATE_CLASS: WTSActive,WTSConnected,WTSConnectQuery,WTSShadow,WTSDisconnected, WTSIdle,WTSListen,WTSReset,WTSDown,WTSInit """ if session['State'] == win32ts.WTSDisconnected: sessionid = session['SessionId'] username = win32ts.WTSQuerySessionInformation( win32ts.WTS_CURRENT_SERVER_HANDLE, sessionid, win32ts.WTSUserName) print('Logging off disconnected user:'******'t kill that session:", e.strerror) else: raise
def delete(name, purge=False, force=False): ''' Remove a user from the minion :param name: The name of the user to delete :param purge: Boolean value indicating that the user profile should also be removed when the user account is deleted. If set to True the profile will be removed. :param force: Boolean value indicating that the user account should be deleted even if the user is logged in. True will log the user out and delete user. CLI Example: .. code-block:: bash salt '*' user.delete name ''' # Check if the user exists try: user_info = win32net.NetUserGetInfo(None, name, 4) except win32net.error as exc: (number, context, message) = exc log.error('User not found: {0}'.format(name)) log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) return False # Check if the user is logged in # Return a list of logged in users try: sess_list = win32ts.WTSEnumerateSessions() except win32ts.error as exc: (number, context, message) = exc log.error('No logged in users found') log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) # Is the user one that is logged in logged_in = False session_id = None for sess in sess_list: if win32ts.WTSQuerySessionInformation(None, sess['SessionId'], win32ts.WTSUserName) == name: session_id = sess['SessionId'] logged_in = True # If logged in and set to force, log the user out and continue # If logged in and not set to force, return false if logged_in: if force: try: win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True) except win32ts.error as exc: (number, context, message) = exc log.error('User not found: {0}'.format(name)) log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) return False else: log.error('User {0} is currently logged in.'.format(name)) return False # Remove the User Profile directory if purge: # If the profile is not defined, get the profile from the registry if user_info['profile'] == '': profiles_dir = __salt__['reg.read_key']( hkey='HKEY_LOCAL_MACHINE', path= 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList', key='ProfilesDirectory') profiles_dir = profiles_dir.replace('%SystemDrive%', os.environ['SystemDrive']) user_info['profile'] = r'{0}\{1}'.format(profiles_dir, name) # Make sure the profile exists before deleting it # Otherwise this will throw an error if os.path.exists(user_info['profile']): sid = getUserSid(name) try: win32profile.DeleteProfile(sid) except pywintypes.error as exc: (number, context, message) = exc log.error('Failed to remove profile for {0}'.format(name)) log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) return False # And finally remove the user account try: win32net.NetUserDel(None, name) except win32net.error as exc: (number, context, message) = exc log.error('Failed to delete user {0}'.format(name)) log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) return False return True
def wts_logoff(sessionid: int, wait: bool = False) -> int: ''' Logoffs session. wait - wait for completion. If the function fails, the return value is zero. ''' return win32ts.WTSLogoffSession(0, sessionid, wait)