def getActiveUser(self): user = "******" try: domain = "" sessionId = GetActiveSessionId() if sessionId != 0xffffffff: user = win32ts.WTSQuerySessionInformation( win32ts.WTS_CURRENT_SERVER_HANDLE, sessionId, win32ts.WTSUserName) domain = win32ts.WTSQuerySessionInformation( win32ts.WTS_CURRENT_SERVER_HANDLE, sessionId, win32ts.WTSDomainName) if domain == "": pass elif domain.lower() != self.getMachineName().lower(): # Use FQDN as user name if computer is part of a domain. try: user = u"%s\\%s" % (domain, user) user = win32security.TranslateName( user, win32api.NameSamCompatible, win32api.NameUserPrincipal) # Check for error because no exception is raised when # running under Windows XP. err = win32api.GetLastError() if err != 0: raise RuntimeError(err, 'TranslateName') except: logging.exception("Error on user name translation.") else: user = u"%s@%s" % (user, domain) except: logging.exception("Error retrieving active user name.") logging.debug("Active user: %s", user) return user
def reListSessions(outFh): protocols = { ts.WTS_PROTOCOL_TYPE_CONSOLE: "console", ts.WTS_PROTOCOL_TYPE_ICA: "citrix", ts.WTS_PROTOCOL_TYPE_RDP: "rdp", } #hostname = api.GetComputerName() hserver = ts.WTS_CURRENT_SERVER_HANDLE currentSessId = ts.WTSGetActiveConsoleSessionId() format = "%(user)-16s %(active)1s%(session)-7s %(id)-7s %(protocol)-8s" print >> outFh, format % dict( user="******", active="", session="SESSION", id="ID", protocol="PROTOCOL", ) for session in ts.WTSEnumerateSessions(hserver): sessionId = session["SessionId"] session["User"] = ts.WTSQuerySessionInformation( hserver, sessionId, ts.WTSUserName) #session["Address"] = ts.WTSQuerySessionInformation(hserver, sessionId, ts.WTSClientAddress) session["Protocol"] = ts.WTSQuerySessionInformation( hserver, sessionId, ts.WTSClientProtocolType) print >> outFh, format % dict( user=session["User"] or "(none)", session=session["WinStationName"], id="(%d)" % session["SessionId"], active="*" if sessionId == currentSessId else "", protocol=protocols[session["Protocol"]], )
def list_sessions(logged_in_users_only=False): ''' List information about the sessions. :param logged_in_users_only: If True, only return sessions with users logged in. :return: A list containing dictionaries of session information. CLI Example: .. code-block:: bash salt '*' rdp.list_sessions ''' ret = list() server = win32ts.WTS_CURRENT_SERVER_HANDLE protocols = { win32ts.WTS_PROTOCOL_TYPE_CONSOLE: 'console', win32ts.WTS_PROTOCOL_TYPE_ICA: 'citrix', win32ts.WTS_PROTOCOL_TYPE_RDP: 'rdp' } statuses = { win32ts.WTSActive: 'active', win32ts.WTSConnected: 'connected', win32ts.WTSConnectQuery: 'connect_query', win32ts.WTSShadow: 'shadow', win32ts.WTSDisconnected: 'disconnected', win32ts.WTSIdle: 'idle', win32ts.WTSListen: 'listen', win32ts.WTSReset: 'reset', win32ts.WTSDown: 'down', win32ts.WTSInit: 'init' } for session in win32ts.WTSEnumerateSessions(server): user = win32ts.WTSQuerySessionInformation(server, session['SessionId'], win32ts.WTSUserName) or None protocol_id = win32ts.WTSQuerySessionInformation( server, session['SessionId'], win32ts.WTSClientProtocolType) status_id = win32ts.WTSQuerySessionInformation(server, session['SessionId'], win32ts.WTSConnectState) protocol = protocols.get(protocol_id, 'unknown') connection_status = statuses.get(status_id, 'unknown') station = session['WinStationName'] or 'Disconnected' connection_info = { 'connection_status': connection_status, 'protocol': protocol, 'session_id': session['SessionId'], 'station': station, 'user': user } if logged_in_users_only: if user: ret.append(connection_info) else: ret.append(connection_info) if not ret: _LOG.warning('No sessions found.') return sorted(ret, key=lambda k: k['session_id'])
def GetUsername(id): server = Ts.WTS_CURRENT_SERVER_HANDLE for session in Ts.WTSEnumerateSessions(server): if session["SessionId"] == id: user = Ts.WTSQuerySessionInformation(server, id, Ts.WTSUserName) domain = Ts.WTSQuerySessionInformation(server, id, Ts.WTSDomainName) return domain, user raise IndexError("No such session")
def getSessionID(username_): domain_ = None if "@" in username_: (username_, domain_) = username_.split("@", 1) localdomain = win32api.GetComputerName() sessions = win32ts.WTSEnumerateSessions(None) session_closing = [] for session in sessions: if not 0 < session["SessionId"] < 65536: continue try: login = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSUserName) if login.lower() != username_.lower(): continue domain = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSDomainName) if domain_ is not None and domain.lower() == localdomain.lower( ): Logger.debug( "Ts session %d is not from the domain user %s but from a local user" % (session["SessionId"], username_)) continue elif domain_ is None and domain.lower() != localdomain.lower(): Logger.debug( "Ts session %d is not from the local user %s but from a domain user" % (session["SessionId"], username_)) continue if Config.checkShell: shell = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSInitialProgram) if not os.path.basename(shell).lower().startswith("ovd"): Logger.debug("Ts session %d is not relative to OVD" % (session["SessionId"])) continue except pywintypes.error, err: if err[0] == 7007: # A close operation is pending on the session. session_closing.append(session) if err[0] == 7022: # Session not found. continue else: Logger.exception("Unable to list session %d" % session["SessionId"]) continue return session["SessionId"]
def EnumServerSessions(server, server_h): for session in Ts.WTSEnumerateSessions(server_h, 1): session["Server"] = server session["hServer"] = server_h try: session["User"] = Ts.WTSQuerySessionInformation( session["hServer"], session["SessionId"], Ts.WTSUserName) session["Protocol"] = Ts.WTSQuerySessionInformation( session["hServer"], session["SessionId"], Ts.WTSClientProtocolType) except Api.error: session["User"] = "" session["Protocol"] = None yield session
def getSessionID(username_): domain_ = None if "@" in username_: (username_, domain_) = username_.split("@", 1) localdomain = win32api.GetComputerName() sessions = win32ts.WTSEnumerateSessions(None) for session in sessions: if not 0 < session["SessionId"] < 65536: continue try: login = win32ts.WTSQuerySessionInformation(None, session["SessionId"], win32ts.WTSUserName) if login.lower() != username_.lower(): continue domain = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSDomainName) if domain_ is not None and domain.lower() == localdomain.lower(): Logger.debug( "Ts session %d is not from the domain user %s but from a local user" % (session["SessionId"], username_)) continue elif domain_ is None and domain.lower() != localdomain.lower(): Logger.debug( "Ts session %d is not from the local user %s but from a domain user" % (session["SessionId"], username_)) continue except pywintypes.error, err: if err[0] == 7007: # A close operation is pending on the session. session_closing.append(session) if err[0] == 7022: # Session not found. continue else: Logger.warn("Unable to list session %d" % (session["SessionId"])) Logger.debug("WTSQuerySessionInformation returned %s" % (err)) continue return session["SessionId"]
def list_user(): pythoncom.CoInitialize() data = {} for session in win32ts.WTSEnumerateSessions( win32ts.WTS_CURRENT_SERVER_HANDLE): sid = session['SessionId'] data[sid] = win32ts.WTSQuerySessionInformation(None, sid, win32ts.WTSUserName) return json.dumps(data)
def getState(session_id): state = win32ts.WTSQuerySessionInformation(None, session_id, win32ts.WTSConnectState) if state in [win32ts.WTSActive, win32ts.WTSConnected, win32ts.WTSInit]: return TS.STATUS_LOGGED if state == win32ts.WTSDisconnected: return TS.STATUS_DISCONNECTED return TS.STATUS_UNKNOWN
def getState(session_id): state = win32ts.WTSQuerySessionInformation(None, session_id, win32ts.WTSConnectState) if state in [win32ts.WTSActive, win32ts.WTSConnected, win32ts.WTSInit]: return "logged" if state == win32ts.WTSDisconnected: return "disconnected" return "unknown"
def lsusers(): """list the users on the machine.""" server = WTSServer(socket.gethostname()) results = [] for session in win32ts.WTSEnumerateSessions(server.handle): session_id = session['SessionId'] state = session['State'] username = win32ts.WTSQuerySessionInformation(server.handle, session_id, win32ts.WTSUserName) results.append(SessionInfo(session_id, state, username)) return results
def wts_user_sessionid(users, only_active: bool = True) -> list: ''' Convert list of users to list of session id's. only_active - return only WTSActive sessions. ''' if isinstance(users, str): user_dict = {users: ''} else: user_dict = {u: '' for u in users} for ses in win32ts.WTSEnumerateSessions(): if only_active: if ses['State'] != win32ts.WTSActive: continue user = win32ts.WTSQuerySessionInformation(None, ses['SessionId'], win32ts.WTSUserName) if user in user_dict.keys(): user_dict[user] = ses['SessionId'] if isinstance(users, str): return user_dict.get(users, -1) else: return [s for s in user_dict.values() if s]
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 get_student_login_sessions(): # Get a list of students that are logged in ret = [] # Get the current user name curr_user = win32api.GetUserName() if UserAccounts.is_user_in_group(curr_user, "OPEStudents"): ret.append(curr_user) # Get the list of users from WTS wts_sessions = [] sessions = win32ts.WTSEnumerateSessions(None, 1, 0) for session in sessions: # Ignore listen status(no user for that), all others query if session['State'] == UserAccounts.WTSActive or \ session['State'] == UserAccounts.WTSDisconnected or \ session['State'] == UserAccounts.WTSConnected: # Found the active session #active_session = session['SessionId'] #station_name = session["WinStationName"] wts_sessions.append(session['SessionId']) # Get the console session (duplicate?) active_session = win32ts.WTSGetActiveConsoleSessionId() if active_session is not None and active_session != UserAccounts.WTS_INVALID_SESSION_ID: wts_sessions.append(active_session) # Convert sessions to users and check their group membership for session in wts_sessions: user_name = win32ts.WTSQuerySessionInformation( None, session, win32ts.WTSUserName) if user_name is not None and user_name != "": if UserAccounts.is_user_in_group(user_name, "OPEStudents"): ret.append(user_name) return ret
""" 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
return session["SessionId"] t0 = time.time() len1 = len(session_closing) len2 = 0 while len1 > 0 and time.time() - t0 < 10: if len2 == len1: time.sleep(0.2) len2 = len1 for i in xrange(len(session_closing)): session = session_closing.pop(0) try: login = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSUserName) if login != username_: continue domain = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSDomainName) if domain.lower() != domain_.lower(): Logger.debug( "Ts session %d is not from the user %s but from a AD user" % (session["SessionId"], username_)) continue if Config.checkShell: shell = win32ts.WTSQuerySessionInformation( None, session["SessionId"], win32ts.WTSInitialProgram)
def list_sessions(logged_in_users_only=False): """ List information about the sessions. .. versionadded:: 2016.11.0 :param logged_in_users_only: If True, only return sessions with users logged in. :return: A list containing dictionaries of session information. CLI Example: .. code-block:: bash salt '*' rdp.list_sessions """ ret = list() server = win32ts.WTS_CURRENT_SERVER_HANDLE protocols = { win32ts.WTS_PROTOCOL_TYPE_CONSOLE: "console", win32ts.WTS_PROTOCOL_TYPE_ICA: "citrix", win32ts.WTS_PROTOCOL_TYPE_RDP: "rdp", } statuses = { win32ts.WTSActive: "active", win32ts.WTSConnected: "connected", win32ts.WTSConnectQuery: "connect_query", win32ts.WTSShadow: "shadow", win32ts.WTSDisconnected: "disconnected", win32ts.WTSIdle: "idle", win32ts.WTSListen: "listen", win32ts.WTSReset: "reset", win32ts.WTSDown: "down", win32ts.WTSInit: "init", } for session in win32ts.WTSEnumerateSessions(server): user = (win32ts.WTSQuerySessionInformation( server, session["SessionId"], win32ts.WTSUserName) or None) protocol_id = win32ts.WTSQuerySessionInformation( server, session["SessionId"], win32ts.WTSClientProtocolType) status_id = win32ts.WTSQuerySessionInformation(server, session["SessionId"], win32ts.WTSConnectState) protocol = protocols.get(protocol_id, "unknown") connection_status = statuses.get(status_id, "unknown") station = session["WinStationName"] or "Disconnected" connection_info = { "connection_status": connection_status, "protocol": protocol, "session_id": session["SessionId"], "station": station, "user": user, } if logged_in_users_only: if user: ret.append(connection_info) else: ret.append(connection_info) if not ret: _LOG.warning("No sessions found.") return sorted(ret, key=lambda k: k["session_id"])
""" import win32security import win32ts import sys sessionIds = [] result = {} wtsUserName = None #print int(windll.kernel32.WTSGetActiveConsoleSessionId()) if len(sys.argv) > 1: sessionId = int(sys.argv[1]) try: wtsUserName = win32ts.WTSQuerySessionInformation( None, sessionId, win32ts.WTSUserName) except: pass for s in win32security.LsaEnumerateLogonSessions(): sessionData = win32security.LsaGetLogonSessionData(s) if (int(sessionData.get("Session")) == sessionId): if wtsUserName and sessionData.get( "UserName").lower() != wtsUserName.lower(): continue sessionData["Sid"] = str(sessionData["Sid"]) sessionData["LogonTime"] = str(sessionData["LogonTime"]) result = sessionData print result else: for s in win32security.LsaEnumerateLogonSessions(): sessionData = win32security.LsaGetLogonSessionData(s)
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 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 rdpSessionIsConnected(): sessionState = win32ts.WTSQuerySessionInformation( None, win32ts.WTS_CURRENT_SESSION, win32ts.WTSConnectState) return sessionState == win32ts.WTSActive