public static IEnumerable <NtToken> GetSessionTokens() { List <NtToken> tokens = new List <NtToken>(); IntPtr pSessions = IntPtr.Zero; int dwSessionCount = 0; try { if (WTSEnumerateSessions(IntPtr.Zero, 0, 1, out pSessions, out dwSessionCount)) { IntPtr current = pSessions; for (int i = 0; i < dwSessionCount; ++i) { WTS_SESSION_INFO session_info = (WTS_SESSION_INFO)Marshal.PtrToStructure(current, typeof(WTS_SESSION_INFO)); SafeKernelObjectHandle handle; if (session_info.State == WTS_CONNECTSTATE_CLASS.WTSActive && WTSQueryUserToken(session_info.SessionId, out handle)) { tokens.Add(NtToken.FromHandle(handle)); } current += Marshal.SizeOf(typeof(WTS_SESSION_INFO)); } } } finally { if (pSessions != IntPtr.Zero) { WTSFreeMemory(pSessions); } } return(tokens); }
public static IEnumerable <int> GetSessionIds() { List <int> sids = new List <int>(); IntPtr pSessions = IntPtr.Zero; int dwSessionCount = 0; try { if (WTSEnumerateSessions(IntPtr.Zero, 0, 1, out pSessions, out dwSessionCount)) { IntPtr current = pSessions; for (int i = 0; i < dwSessionCount; ++i) { WTS_SESSION_INFO session_info = (WTS_SESSION_INFO)Marshal.PtrToStructure(current, typeof(WTS_SESSION_INFO)); sids.Add(session_info.SessionId); current += Marshal.SizeOf(typeof(WTS_SESSION_INFO)); } } } finally { if (pSessions != IntPtr.Zero) { WTSFreeMemory(pSessions); } } return(sids); }
public static List <TerminalSessionData> ListSessions(string ServerName) { IntPtr server = IntPtr.Zero; List <TerminalSessionData> ret = new List <TerminalSessionData>(); server = OpenServer(ServerName); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int64 current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; ret.Add(new TerminalSessionData(si.SessionID, si.State, si.pWinStationName)); } WTSFreeMemory(ppSessionInfo); } } finally { CloseServer(server); } return(ret); }
/// <summary> /// The SessionEnumeration function retrieves a list of WTS_SESSION_INFO /// on a current terminal server. /// </summary> /// <returns>a list of WTS_SESSION_INFO o a current terminal server</returns> public static WTS_SESSION_INFO[] SessionEnumeration() { // Set handle of terminal server as the current terminal server int hServer = 0; bool retVal; long lpBuffer = 0; int count = 0; long p; WTS_SESSION_INFO session_Info = new WTS_SESSION_INFO(); WTS_SESSION_INFO[] arrSessionInfo; retVal = WTSEnumerateSessions(hServer, 0, 1, ref lpBuffer, ref count); arrSessionInfo = new WTS_SESSION_INFO[0]; if (retVal) { arrSessionInfo = new WTS_SESSION_INFO[count]; p = lpBuffer; for (int i = 0; i < count; i++) { arrSessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure( new IntPtr(p), session_Info.GetType()); p += Marshal.SizeOf(session_Info.GetType()); } WTSFreeMemory(new IntPtr(lpBuffer)); } else { // Insert Error Reactive Here } return(arrSessionInfo); }
// Ref: https://stackoverflow.com/a/40964859 private void BlockComputer() { //increment number of times blocked Increment_num_block(); //Update last time blocked epoch_old = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); //dont reset the blocking counter reset = false; IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 currentSession = (int)ppSessionInfo; if (retval == 0) { return; } for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) { WTSDisconnectSession(IntPtr.Zero, si.SessionID, false); } currentSession += dataSize; } WTSFreeMemory(ppSessionInfo); }
// Phương thức lấy danh sách các phiên đang hoạt động public static List <Session> ListUsers(String ServerName) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); List <Session> listSessions = new List <Session>(); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; IntPtr sessionIDPtr = IntPtr.Zero; IntPtr statePtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSSessionId, out sessionIDPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSConnectState, out statePtr, out bytes); if (Marshal.PtrToStringAnsi(domainPtr) != "") { Session session = new Session(Marshal.PtrToStringAnsi(userPtr), (int)Marshal.PtrToStructure <Int64>(sessionIDPtr), Marshal.PtrToStringAnsi(domainPtr), (CONNECTSTATE_CLASS)Marshal.PtrToStructure <Int64>(statePtr)); listSessions.Add(session); //Console.WriteLine("Domain and User + ID: " + Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr) // + "\\" + Marshal.PtrToStructure<Int64>(sessionIDPtr) // + "\\" + Enum.GetName(typeof(CONNECTSTATE_CLASS), Marshal.PtrToStructure<Int64>(statePtr))); } WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); WTSFreeMemory(sessionIDPtr); WTSFreeMemory(statePtr); } WTSFreeMemory(SessionInfoPtr); } return(listSessions); } finally { CloseServer(serverHandle); } }
public static List <SessionInfo> ListSessions(string serverName, string userName, string domainName, string clientName, WTS_CONNECTSTATE_CLASS?state) { IntPtr server = IntPtr.Zero; List <SessionInfo> sessions = new List <SessionInfo>(); server = OpenServer(serverName); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { SessionInfo sessionInfo = new SessionInfo(); WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; sessionInfo.Id = si.SessionID; sessionInfo.UserName = QuerySessionInfo(server, sessionInfo.Id, WTS_INFO_CLASS.WTSUserName); sessionInfo.DomainName = QuerySessionInfo(server, sessionInfo.Id, WTS_INFO_CLASS.WTSDomainName); sessionInfo.ClientName = QuerySessionInfo(server, sessionInfo.Id, WTS_INFO_CLASS.WTSClientName); sessionInfo.State = si.State; if (userName != null || domainName != null || clientName != null || state != null) //In this case, the caller is asking to return only matching sessions { if (userName != null && !String.Equals(userName, sessionInfo.UserName, StringComparison.CurrentCultureIgnoreCase)) { continue; //Not matching } if (clientName != null && !String.Equals(clientName, sessionInfo.ClientName, StringComparison.CurrentCultureIgnoreCase)) { continue; //Not matching } if (domainName != null && !String.Equals(domainName, sessionInfo.DomainName, StringComparison.CurrentCultureIgnoreCase)) { continue; //Not matching } if (state != null && sessionInfo.State != state.Value) { continue; } } sessions.Add(sessionInfo); } WTSFreeMemory(ppSessionInfo); } } finally { CloseServer(server); } return(sessions); }
public void LockWorkstation() { var lockState = WorkstationHelper.GetActiveSessionLockState(); if (lockState == WorkstationHelper.LockState.Unlocked) { IntPtr ppSessionInfo = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); var currentSession = ppSessionInfo; uint bytes = 0; if (retval == 0) { return; } WriteLine("Query sessions"); for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(IntPtr.Zero, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(IntPtr.Zero, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); var domain = Marshal.PtrToStringAnsi(domainPtr); var userName = Marshal.PtrToStringAnsi(userPtr); var sessionFullName = domain + "\\" + userName; WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); // Note: it might be a good idea to limit session disconnects only to those activated by triggered device //if (sessionFullName == sessionTolock) if (!string.IsNullOrWhiteSpace(domain) && !string.IsNullOrWhiteSpace(userName)) { if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) { WriteLine($"Disconnecting session: {sessionFullName}"); bool disconnected = WTSDisconnectSession(IntPtr.Zero, si.SessionID, true); WriteLine($"Session disconnected: {disconnected}"); } else { WriteLine($"Session inactive: {sessionFullName}"); } } else { WriteLine($"Session skipped: {sessionFullName}"); } } WTSFreeMemory(ppSessionInfo); } }
public static List <string> ListUsers(String ServerName) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; IntPtr clientNamePtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 currentSession = (int)SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSClientName, out clientNamePtr, out bytes); if (Marshal.PtrToStringAnsi(domainPtr).Length > 0 && Marshal.PtrToStringAnsi(userPtr).Length > 0) { if (Marshal.PtrToStringAnsi(clientNamePtr).Length < 1) { resultList.Add(Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr) + "\tSessionID: " + si.SessionID + "\tClientName: n/a"); } else { resultList.Add(Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr) + "\tSessionID: " + si.SessionID + "\tClientName: " + Marshal.PtrToStringAnsi(clientNamePtr)); } } WTSFreeMemory(clientNamePtr); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } finally { CloseServer(serverHandle); } return(resultList); }
internal TerminalSession(TerminalServer server, WTS_SESSION_INFO info) { _server = server; _sessionId = info.SessionId; _winStation = info.WinStationName; _state = (TerminalSessionState)(info.State); _client = new TerminalSessionClientInfo(this); }
public static bool IsHasNonActiveSession() { IntPtr buffer = IntPtr.Zero; int count = 0; // получаем список сессий, в которых выполнен вход if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref buffer, ref count)) { WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[count]; // самая сложная часть: // аккуратно преобразовать неуправляемую память в управляемую for (int index = 0; index < count; index++) { sessionInfo[index] = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)((int)buffer + (Marshal.SizeOf(new WTS_SESSION_INFO()) * index)), typeof(WTS_SESSION_INFO)); } int activeSessId = -1; int targetSessId = -1; // получаем Id активного, и неактивного сеанса // 0 пропускаем, там всегда "Services" for (int i = 1; i < count; i++) { if (sessionInfo[i].State == WTS_CONNECTSTATE_CLASS.WTSDisconnected) { targetSessId = sessionInfo[i].SessionId; } else if (sessionInfo[i].State == WTS_CONNECTSTATE_CLASS.WTSActive) { activeSessId = sessionInfo[i].SessionId; } } if ((activeSessId > 0) && (targetSessId > 0)) { // если есть неактивный сеанс // обязательно чистим память WTSFreeMemory(buffer); return(true); } else { // если неактивных нет. просто отключаемся (переходим на экран выбора пользователя) // обязательно чистим память WTSFreeMemory(buffer); return(false); } } // обязательно чистим память WTSFreeMemory(buffer); return(false); }
public void Poll() { IntPtr WTS_CURRENT_SERVER_HANDLE = (IntPtr)null; Stopwatch sw = new Stopwatch(); sw.Start(); try { IntPtr SessionInfoPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref SessionInfoPtr, ref sessionCount); Int64 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; if (retVal != 0) { Dictionary <int, int> cs = new Dictionary <int, int>(); for (int i = 0; i < this.Count; i++) { cs[this[i].id] = i; } for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(currentSession, typeof(WTS_SESSION_INFO)); currentSession = new IntPtr(currentSession.ToInt64() + dataSize); if (si.SessionID == 0 || si.SessionID == 65536) { continue; } if (!cs.ContainsKey(si.SessionID)) { Add(si.SessionID); } else { cs.Remove(si.SessionID); } } foreach (KeyValuePair <int, int> entry in cs) { this.Remove(this[entry.Value]); } WTSFreeMemory(SessionInfoPtr); } } catch (Exception e) { eventLog1.WriteEntry(e.Message + e.StackTrace, EventLogEntryType.Error, 1); } sw.Stop(); ticks = sw.ElapsedMilliseconds; }
public List <SessionInfo> ListUsers(String ServerName) { List <SessionInfo> result = new List <SessionInfo>(); IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); result.Add( new SessionInfo { UserName = Marshal.PtrToStringAnsi(userPtr), DomainName = Marshal.PtrToStringAnsi(domainPtr), SessionID = si.SessionID, WinStationName = si.pWinStationName, State = si.State } ); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } return(result); }
/// <summary> /// 以当前登录系统的用户角色权限启动指定的进程 /// </summary> /// <param name="ChildProcName">指定的进程(全路径)</param> public static void CreateProcess(string ChildProcName) { IntPtr ppSessionInfo = IntPtr.Zero; UInt32 SessionCount = 0; if (WTSEnumerateSessions( (IntPtr)WTS_CURRENT_SERVER_HANDLE, // Current RD Session Host Server handle would be zero. 0, // This reserved parameter must be zero. 1, // The version of the enumeration request must be 1. ref ppSessionInfo, // This would point to an array of session info. ref SessionCount // This would indicate the length of the above array. )) { for (int nCount = 0; nCount < SessionCount; nCount++) { WTS_SESSION_INFO tSessionInfo = (WTS_SESSION_INFO)Marshal.PtrToStructure(ppSessionInfo + nCount * Marshal.SizeOf(typeof(WTS_SESSION_INFO)), typeof(WTS_SESSION_INFO)); if (WTS_CONNECTSTATE_CLASS.WTSActive == tSessionInfo.State) { IntPtr hToken = IntPtr.Zero; if (WTSQueryUserToken(tSessionInfo.SessionID, out hToken)) { PROCESS_INFORMATION tProcessInfo; STARTUPINFO tStartUpInfo = new STARTUPINFO(); tStartUpInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO)); bool ChildProcStarted = CreateProcessAsUser( hToken, // Token of the logged-on user. ChildProcName, // Name of the process to be started. null, // Any command line arguments to be passed. IntPtr.Zero, // Default Process' attributes. IntPtr.Zero, // Default Thread's attributes. false, // Does NOT inherit parent's handles. 0, // No any specific creation flag. null, // Default environment path. null, // Default current directory. ref tStartUpInfo, // Process Startup Info. out tProcessInfo // Process information to be returned. ); if (ChildProcStarted) { CloseHandle(tProcessInfo.hThread); CloseHandle(tProcessInfo.hProcess); } else { ShowServiceMessage("CreateProcessAsUser失败", "CreateProcess"); } CloseHandle(hToken); break; } } } WTSFreeMemory(ppSessionInfo); } }
//static void Main(string[] args) //{ // Console.WriteLine(GetActiveConsoleUserWithDomain()); // Console.Read(); //} public static string GetActiveConsoleUserWithDomain() { string ServerName = Environment.MachineName; string UserName = ""; IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; IntPtr sessionInfoEx = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSSessionInfoEx, out sessionInfoEx, out bytes); WTSINFOEX InfoEx = (WTSINFOEX)Marshal.PtrToStructure <WTSINFOEX>(sessionInfoEx); ; //Console.WriteLine(si.pWinStationName + "," + si.State.ToString() + ",Domain and User: "******"\\" + Marshal.PtrToStringAnsi(userPtr)); if (si.pWinStationName == "Console" && InfoEx.Data.WTSInfoExLevel1.SessionFlags == 1) { UserName = Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr); } WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); WTSFreeMemory(sessionInfoEx); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } return(UserName); }
public static string[] ListUsers(String ServerName) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 currentSession = (int)SessionInfoPtr; uint bytes = 0; string[] logon_users = new string[1]; int k = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); //Console.WriteLine("Domain and User: "******"\\" + Marshal.PtrToStringAnsi(userPtr)); if (!Marshal.PtrToStringAnsi(userPtr).ToString().Equals("")) { k++; Array.Resize(ref logon_users, k); logon_users[k - 1] = Marshal.PtrToStringAnsi(userPtr).ToString(); } WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } // WTSFreeMemory(SessionInfoPtr); } return(logon_users); } catch { return(null); } finally { CloseServer(serverHandle); } }
public static bool IsUserLoggedOn(IntPtr server, string queryUserName) { IntPtr buffer = IntPtr.Zero; int count = 0; bool isUserLoggedOn = false; try { int retval = WTSEnumerateSessions(server, 0, 1, ref buffer, ref count); int dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int64 current = (int)buffer; if (retval != 0) { for (int i = 0; i < count; i++) { var bufferTwo = IntPtr.Zero; uint bytesReturned = 0; WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; //windowsUser.SessionId = Convert.ToUInt32(si.SessionID); try { string loggedOnUser = string.Empty; // Get the username of the Terminal Services user. if (WTSQuerySessionInformation(server, si.SessionID, WTS_INFO_CLASS.WTSUserName, out buffer, out bytesReturned) == true) { loggedOnUser = Marshal.PtrToStringAnsi(buffer).Trim(); } if (loggedOnUser.Equals(queryUserName, StringComparison.OrdinalIgnoreCase)) { isUserLoggedOn = true; break; } } finally { WTSFreeMemory(bufferTwo); } } } } finally { WTSFreeMemory(buffer); } return(isUserLoggedOn); }
private uint GetUserSession(string partofusername, WTS_CONNECTSTATE_CLASS sessionstate) { // get the first found user session with desired name port or - if name part string is null - with desired sessionstate uint sessionId = 0xFFFFFFFF; IntPtr pSessionInfo = IntPtr.Zero; int sessionCount = 0; int dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); if (WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessionInfo, ref sessionCount) != 0) // IntPtr.Zero = WTS_CURRENT_SERVER_HANDLE { // get information array of logon sessions IntPtr currentSessionInfo = pSessionInfo; for (int i = 0; i < sessionCount; i++) { // enumerate sessions (walk through array) WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(currentSessionInfo, typeof(WTS_SESSION_INFO)); currentSessionInfo += dataSize; if (partofusername != null) { // search for session with part of username IntPtr nameBuffer; int nameLen; // query for user name of session if (WTSQuerySessionInformation(IntPtr.Zero, si.SessionID, WTS_INFO_CLASS.WTSUserName, out nameBuffer, out nameLen)) { // Session 0 and "listening" session 65536 return username "\0" string username = Marshal.PtrToStringAnsi(nameBuffer); if (username.Length > 0) { // session has a user if (username.ToLower().Contains(partofusername.ToLower())) { // user name of session contains search word sessionId = si.SessionID; break; } } // free memory WTSFreeMemory(nameBuffer); } } else { // check if session has desired state and is not the "service" session 0 if ((si.State == sessionstate) && (si.SessionID != 0)) { sessionId = si.SessionID; break; } } } // free memory WTSFreeMemory(pSessionInfo); } return(sessionId); // retrun found session id or 0xFFFFFFFF }
public static List <String> ListSessions(String ServerName) { IntPtr server = IntPtr.Zero; server = OpenServer(ServerName); List <String> ret = new List <string>(); ret.Add("SessionID\tState\tpWinStationName\tWTSClientIP\tWTSClientName\tWTSDomainName\tWTSUserName"); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int64 current = (Int64)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; string clientname = GetWTSQuerySessionInformation(server, si.SessionID, WTS_INFO_CLASS.WTSClientName); string domainname = GetWTSQuerySessionInformation(server, si.SessionID, WTS_INFO_CLASS.WTSDomainName); string username = GetWTSQuerySessionInformation(server, si.SessionID, WTS_INFO_CLASS.WTSUserName); if (("console" == si.pWinStationName.ToLower()) || ("services" == si.pWinStationName.ToLower())) { ret.Add(si.SessionID + "\t" + si.State + "\t" + si.pWinStationName + "\t" + ConsoleServices.ConsoleManager.GetIPAddress() + "\t" + clientname + "\t" + domainname + "\t" + username); } else { ret.Add(si.SessionID + "\t" + si.State + "\t" + si.pWinStationName + "\t" + GetIPAddress(server, si.SessionID) + "\t" + clientname + "\t" + domainname + "\t" + username); } } WTSFreeMemory(ppSessionInfo); } } finally { CloseServer(server); } return(ret); }
/// <summary> /// Get a List of all Sessions on a server and IP address. /// </summary> /// <param name="ServerName"></param> /// <returns></returns> public static List <String> ListSessions(String ServerName) { IntPtr server = IntPtr.Zero; List <String> ret = new List <string>(); server = OpenServer(ServerName); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; #region OTsSession uint returned = 0;; TsSession oTsSession = new TsSession(); //IP address IntPtr addr = IntPtr.Zero; if (WTSQuerySessionInformation(server, si.SessionID, WTS_INFO_CLASS.WTSClientAddress, out addr, out returned) == true) { _WTS_CLIENT_ADDRESS obj = new _WTS_CLIENT_ADDRESS(); obj = (_WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(addr, obj.GetType()); oTsSession.IpAddress = obj.Address[2] + "." + obj.Address[3] + "." + obj.Address[4] + "." + obj.Address[5]; } #endregion ret.Add(si.SessionID + " " + si.State + " " + si.pWinStationName + " " + oTsSession.IpAddress); } WTSFreeMemory(ppSessionInfo); } } finally { CloseServer(server); } return(ret); }
//основная функция, ради которой существует этот файл. // она получает список залогиненных юзеров и определяет, принадлежит ли // к ним username. public static bool IsActualUser(String ServerName, string username) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; bool result = false; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); // UserName and Domain is printed out here //Console.WriteLine("Domain and User: {0}\\{1}", Marshal.PtrToStringAnsi(domainPtr), Marshal.PtrToStringAnsi(userPtr)); if (Marshal.PtrToStringAnsi(userPtr) == username) { //юзер настоящий result = true; } WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } return(result); } catch { CloseServer(serverHandle); return(false); } }
public static uint GetSessionIdByUsername(string username) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(Environment.MachineName); uint sessionid = INVALID_SESSION_ID; try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); Console.WriteLine(Marshal.PtrToStringAnsi(userPtr)); if (Marshal.PtrToStringAnsi(userPtr).Equals(username)) { Console.WriteLine(username); Console.WriteLine(si.SessionID); sessionid = (uint)si.SessionID; break; } WTSFreeMemory(userPtr); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } return(sessionid); }
public static List <SessionInfo> GetServerActiveSessions(string serverName) { IntPtr server = IntPtr.Zero; List <SessionInfo> sessionInfos = new List <SessionInfo>(); server = OpenServer(serverName); if (server != IntPtr.Zero) { try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; if (WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count)) { Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 current = (int)ppSessionInfo; for (int i = 0; i < count; i++) { SessionInfo sessionInfo = new SessionInfo(); WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; sessionInfo.ApplicationName = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSApplicationName); sessionInfo.ClientAddress = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientAddress); sessionInfo.ClientBuildNumber = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientBuildNumber); sessionInfo.ClientDirectory = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientDirectory); sessionInfo.ClientDisplay = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientDisplay); sessionInfo.ClientDirectory = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientDirectory); sessionInfo.ClientHardwareId = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientHardwareId); sessionInfo.ClientName = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientName); sessionInfo.ClientProductId = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSClientProductId); sessionInfo.ClientProtocolType = QuerySessionInfo <short>(server, si.SessionID, WTS_INFO_CLASS.WTSClientProtocolType); sessionInfo.ConnectState = QuerySessionInfo <WTS_CONNECTSTATE_CLASS>(server, si.SessionID, WTS_INFO_CLASS.WTSConnectState); sessionInfo.DomainName = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSDomainName); sessionInfo.InitialProgram = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSInitialProgram); sessionInfo.OEMId = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSOEMId); sessionInfo.SessionId = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSSessionId); sessionInfo.UserName = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSUserName); sessionInfo.WinStationName = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSWinStationName); sessionInfo.WorkingDirectory = QuerySessionInfo(server, si.SessionID, WTS_INFO_CLASS.WTSWorkingDirectory); } WTSFreeMemory(ppSessionInfo); } } finally { CloseServer(server); } } return(sessionInfos); }
public static UserInfo GetUser(String ServerName, string user) { IntPtr serverHandle = IntPtr.Zero; serverHandle = OpenServer(ServerName); UserInfo result = new UserInfo(); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 currentSession = (int)SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); string ThisUser = Marshal.PtrToStringAnsi(userPtr); if (ThisUser == user) { result.Domain = Marshal.PtrToStringAnsi(domainPtr); result.User = ThisUser; result.SessionID = si.SessionID; } WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } return(result); }
public static IntPtr GetCurrentUserToken() { IntPtr currentToken = IntPtr.Zero; IntPtr primaryToken = IntPtr.Zero; IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; int dwSessionId = 0; IntPtr hUserToken = IntPtr.Zero; IntPtr hTokenDup = IntPtr.Zero; IntPtr pSessionInfo = IntPtr.Zero; int dwCount = 0; WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref dwCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 current = (int)pSessionInfo; for (int i = 0; i < dwCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); if (WTS_CONNECTSTATE_CLASS.WTSActive == si.State) { dwSessionId = si.SessionID; break; } current += dataSize; } WTSFreeMemory(pSessionInfo); bool bRet = WTSQueryUserToken(dwSessionId, out currentToken); if (bRet == false) { return(IntPtr.Zero); } bRet = DuplicateTokenEx(currentToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken); if (bRet == false) { return(IntPtr.Zero); } return(primaryToken); }
private static List <WTS_SESSION_INFO> ListSessions(ITracer tracer) { IntPtr sessionInfo = IntPtr.Zero; IntPtr server = IntPtr.Zero; List <WTS_SESSION_INFO> output = new List <WTS_SESSION_INFO>(); try { int count = 0; int retval = WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref sessionInfo, ref count); if (retval != 0) { int dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); long current = sessionInfo.ToInt64(); for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; output.Add(si); } } else { TraceWin32Error(tracer, "Unable to enumerate sessions on the current host."); } } catch (Exception exception) { output.Clear(); tracer.RelatedError(exception.ToString()); } finally { if (sessionInfo != IntPtr.Zero) { WTSFreeMemory(sessionInfo); } } return(output); }
private static void GetClientInfos(TerminalServer terminalServer) { try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; Int32 FRetVal = WTSEnumerateSessions(terminalServer.ServerPointer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { terminalServer.Sessions = new List <Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; for (int i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i * Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure(session_ptr, typeof(WTS_SESSION_INFO)); Session session = new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates)(int)sessionInfo[i].State, WindowsStationName = string.IsNullOrWhiteSpace(sessionInfo[i].pWinStationName) ? "RPD-Tcp#?" : sessionInfo[i].pWinStationName, ServerName = terminalServer.ServerName }; session.Client = GetClientInfoForSession(terminalServer.ServerPointer, session.SessionId); session.Client.Status = Enum.GetName(typeof(ConnectionStates), session.State).Replace("WTS", ""); terminalServer.Sessions.Add(session); } WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Log.Info("Error enumerating RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }
public static void ListUsers(String ServerName) { IntPtr serverHandle = IntPtr.Zero; List <String> resultList = new List <string>(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); Console.WriteLine(si.pWinStationName + "," + si.State.ToString() + ",Domain and User: "******"\\" + Marshal.PtrToStringAnsi(userPtr)); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } }
internal static List<int> GetSessionIDs(IntPtr server) { List<int> sessionIds = new List<int>(); IntPtr buffer = IntPtr.Zero; int count = 0; int retval = WTSEnumerateSessions(server, 0, 1, ref buffer, ref count); int dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int64 current = (int)buffer; if (retval != 0) { for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; sessionIds.Add(si.SessionID); } WTSFreeMemory(buffer); } return sessionIds; }
public static List <UInt32> ListSessions() { IntPtr server = IntPtr.Zero; List <UInt32> ret = new List <UInt32>(); server = OpenServer("localhost"); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO)); current += dataSize; if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) { ret.Add((UInt32)si.SessionID); } } } } finally { } return(ret); }
private static void GetClientInfos(TerminalServer terminalServer) { try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; Int32 FRetVal = WTSEnumerateSessions(terminalServer.ServerPointer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { terminalServer.Sessions = new List<Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; for (int i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i*Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO) Marshal.PtrToStructure(session_ptr, typeof (WTS_SESSION_INFO)); Session session = new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates) (int) sessionInfo[i].State, WindowsStationName = string.IsNullOrWhiteSpace(sessionInfo[i].pWinStationName) ? "RPD-Tcp#?" : sessionInfo[i].pWinStationName, ServerName = terminalServer.ServerName }; session.Client = GetClientInfoForSession(terminalServer.ServerPointer, session.SessionId); session.Client.Status = Enum.GetName(typeof(ConnectionStates), session.State).Replace("WTS", ""); terminalServer.Sessions.Add(session); } WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Log.Info("Error enumerating RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }
public static extern unsafe bool WTSEnumerateSessions( SafeTerminalServerHandle hServer, uint Reserved, uint Version, out WTS_SESSION_INFO* ppSessionInfo, out int pCount);
public static TerminalServer GetSessions(string ServerName) { TerminalServer Data = new TerminalServer {ServerName = ServerName}; IntPtr ptrOpenedServer = IntPtr.Zero; try { ptrOpenedServer = WTSOpenServer(ServerName); if (ptrOpenedServer == IntPtr.Zero) { Data.IsATerminalServer = false; return Data; } Data.ServerPointer = ptrOpenedServer; Data.IsATerminalServer = true; IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; try { Int32 FRetVal = WTSEnumerateSessions(ptrOpenedServer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { Data.Sessions = new List<Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; int i; for (i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i*Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO) Marshal.PtrToStructure(session_ptr, typeof (WTS_SESSION_INFO)); Data.Sessions.Add(new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates) (int) sessionInfo[i].State, WindowsStationName = sessionInfo[i].pWinStationName, ServerName = ServerName }); } WTSFreeMemory(ppSessionInfo); strSessionsInfo[] tmpArr = new strSessionsInfo[sessionInfo.GetUpperBound(0) + 1]; for (i = 0; i <= tmpArr.GetUpperBound(0); i++) { tmpArr[i].SessionID = sessionInfo[i].SessionID; tmpArr[i].StationName = sessionInfo[i].pWinStationName; tmpArr[i].ConnectionState = GetConnectionState(sessionInfo[i].State); } // ERROR: Not supported in C#: ReDimStatement } } catch (Exception ex) { Log.Error("Get Sessions Inner", ex); Data.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } } catch (Exception ex) { Log.Info("Get Sessions Outer", ex); Data.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } WTS_PROCESS_INFO[] plist = WTSEnumerateProcesses(ptrOpenedServer, Data); //Get ProcessID of TS Session that executed this TS Session Int32 active_process = GetCurrentProcessId(); Int32 active_session = 0; bool success1 = ProcessIdToSessionId(active_process, ref active_session); if (active_session <= 0) success1 = false; if (Data != null && Data.Sessions != null) { foreach (Session s in Data.Sessions) { if (s.Client == null) s.Client = new Client(); WTS_CLIENT_INFO ClientInfo = LoadClientInfoForSession(Data.ServerPointer, s.SessionId); s.Client.Address = ClientInfo.Address; s.Client.AddressFamily = ClientInfo.AddressFamily; s.Client.ClientName = ClientInfo.WTSClientName; s.Client.DomianName = ClientInfo.WTSDomainName; s.Client.StationName = ClientInfo.WTSStationName; s.Client.Status = ClientInfo.WTSStatus; s.Client.UserName = ClientInfo.WTSUserName; s.IsTheActiveSession = false; if (success1 && s.SessionId == active_session) s.IsTheActiveSession = true; } } WTSCloseServer(ptrOpenedServer); return Data; }
private void SwitchUser() { IntPtr buffer = IntPtr.Zero; int count = 0; // получаем список сессий, в которых выполнен вход if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref buffer, ref count)) { WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[count]; // самая сложная часть: // аккуратно преобразовать неуправляемую память в управляемую for (int index = 0; index < count; index++) sessionInfo[index] = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)((int)buffer + (Marshal.SizeOf(new WTS_SESSION_INFO()) * index)), typeof(WTS_SESSION_INFO)); int activeSessId = -1; int targetSessId = -1; // получаем Id активного, и неактивного сеанса // 0 пропускаем, там всегда "Services" for (int i = 1; i < count; i++) { if (sessionInfo[i].State == WTS_CONNECTSTATE_CLASS.WTSDisconnected) targetSessId = sessionInfo[i].SessionId; else if (sessionInfo[i].State == WTS_CONNECTSTATE_CLASS.WTSActive) activeSessId = sessionInfo[i].SessionId; } if ((activeSessId > 0) && (targetSessId > 0)) { // если есть неактивный сеанс, то переключаемся на него. WTSConnectSession(Convert.ToUInt64(targetSessId), Convert.ToUInt64(activeSessId), "", false); } else { // если неактивных нет. просто отключаемся (переходим на экран выбора пользователя) WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE, activeSessId, false); } } // обязательно чистим память WTSFreeMemory(buffer); }