private void SearchActiveSessions(LogFileParser.foundElementInfo [] selectedUserPCs, string selectedUser)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            for (int i = 0; i < selectedUserPCs.Length; i++)
            {
                try {
                    Ping        ping        = new Ping();
                    PingOptions pingOptions = new PingOptions();
                    pingOptions.DontFragment = true;
                    string    data   = "fff";
                    byte[]    buffer = Encoding.ASCII.GetBytes(data);
                    PingReply reply  = ping.Send(selectedUserPCs[i].name, 120, buffer, pingOptions);
                    if (reply.Status == IPStatus.Success)
                    {
                        using (ITerminalServer server = manager.GetRemoteServer(selectedUserPCs[i].name)) {
                            server.Open();
                            foreach (ITerminalServicesSession session in server.GetSessions())
                            {
                                if (session.UserName.ToLower() == selectedUser.ToLower() && session.ConnectionState == ConnectionState.Active)
                                {
                                    selectedUserPCs[i].name = "->" + selectedUserPCs[i].name + "<-";
                                }
                            }
                        }
                    }
                } catch { }
            }
        }
        private ITerminalServer GetServer()
        {
            var mgr = new TerminalServicesManager();

            if (string.IsNullOrWhiteSpace(ComputerName))
            {
                // Local Machine
                return(mgr.GetLocalServer());
            }
            else
            {
                // Remote Machine
                return(mgr.GetRemoteServer(ComputerName));
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var manager = new TerminalServicesManager();

            using (var server = manager.GetRemoteServer("server"))
            {
                server.Open();
                foreach (var session in server.GetSessions())
                {
                    if (session.ConnectionState == ConnectionState.Active)
                    {
                        Console.WriteLine(session.ClientName);
                    }
                }
            }
        }
Exemple #4
0
        private void LoadTSUsers()
        {
            try
            {
                listTSUser.Clear();
                TerminalServicesManager tsManager = new TerminalServicesManager();
                string[] massHosts = new string[] { "TS1", "TS2", "TS3", "TS4", "TS5", "TS6", "TS7" };

                foreach (var host in massHosts)
                {
                    using (ITerminalServer server = tsManager.GetRemoteServer(host))
                    {
                        server.Open();
                        foreach (ITerminalServicesSession session in server.GetSessions())
                        {
                            NTAccount account = session.UserAccount;
                            if (account != null)
                            {
                                TSUser user = new TSUser()
                                {
                                    DomainName        = session.DomainName,
                                    PCName            = session.ClientName,
                                    TSName            = host,
                                    UserName          = session.UserName,
                                    ConnectionState   = session.ConnectionState.ToString(),
                                    WindowStationName = session.WindowStationName,
                                    UserAccount       = account.ToString(),
                                };
                                Dispatcher.Invoke((Action)(() =>
                                {
                                    listTSUser.Add(user);
                                }));
                            }
                        }
                    }
                }

                foreach (var user in listTSUser)
                {
                    user.ClientIPAddress = (from i in listPcIPAndPcName where i.PcName.ToLower() == user.PCName.ToLower() select i.PcIP).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                Bindings.StatusBarText = ex.Message;
            }
        }
        public static bool SendMessage(string message)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer(ServerIPAddress))
            {
                server.Open();
                var session = server.GetSessions().Where(x => x.UserName == UserNameOnServer).FirstOrDefault();
                if (session != null)
                {
                    var response = session.MessageBox(message, "Message for user", RemoteMessageBoxButtons.YesNo,
                                                      RemoteMessageBoxIcon.Question, RemoteMessageBoxDefaultButton.Button2, RemoteMessageBoxOptions.None, TimeSpan.Zero, true);
                    return(response == RemoteMessageBoxResult.Yes);
                }
            }
            return(false);
        }
        public static void Main(string[] args)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer("your-server-name"))
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    NTAccount account = session.UserAccount;
                    if (account != null)
                    {
                        Console.WriteLine(account);
                    }
                }
            }
        }
Exemple #7
0
        private static ITerminalServicesSession GetSession()
        {
            ITerminalServicesManager manager = new TerminalServicesManager();
            ITerminalServicesSession session;

            using (ITerminalServer server = manager.GetRemoteServer("192.168.0.10"))
            {
                server.Open();
                int i = 0;

                IList <ITerminalServicesSession> sessionsList = server.GetSessions();
                do
                {
                    session = sessionsList[i];
                    i++;
                } while (i < sessionsList.Count && session.UserName.ToUpper() != "MEDIA SERVER");
            }
            return(session.UserName.ToUpper() == "MEDIA SERVER" && session != null ? session : null);
        }
Exemple #8
0
        //Возвращает список сеансов с сервера(имя сервера в качестве параметра)
        public void getSessionList()
        {
            IList <ITerminalServicesSession> serverSession;
            int countSession = 0;

            serverSessionList.Clear();

            //Далее идет код для подключения к серверу
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer(serverName))
            {
                server.Open();

                // Перебираем все сеансы на сервере.
                try
                {
                    serverSession = server.GetSessions();
                }
                catch (Exception ex)
                {
                    serverStatus  = ex.Message;
                    serverSession = null;
                    log.appendLog(MethodBase.GetCurrentMethod().ReflectedType.Name + "\n" + MethodBase.GetCurrentMethod().Name + "\n" + ex + "\n" + Application.UserAppDataPath);
                }
                server.Close();
                if (serverSession != null)
                {
                    foreach (ITerminalServicesSession session in serverSession)
                    {
                        //Фильтруем системный сеанс с Id 0. Отбираем сеансы в статусе Active или в статусе Disconnected, но не с пустым именем
                        if (session.SessionId != 0 && ((session.ConnectionState == ConnectionState.Active) || (session.ConnectionState == ConnectionState.Disconnected && session.UserName != "")))
                        {
                            serverSessionList.Add(session);
                            countSession++;
                        }
                    }
                }
            }
            sessionCount = countSession;
            lastCheck    = DateTime.Now.ToString();
        }
Exemple #9
0
        private static int CountUsers()
        {
            int NbrUsers = 0;
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer(Settings.Ip))
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    NTAccount account = session.UserAccount;

                    if (account != null)
                    {
                        NbrUsers++;
                    }
                }
            }
            return(NbrUsers);
        }
Exemple #10
0
        /// <summary>
        ///     Overrides the <see cref="Execute"/> method exposed by the <see cref="SwedishCodeActivity{T}"/> class.
        /// </summary>
        /// <param name="context">The execution context passed when invoked.</param>
        /// <returns>A string back to the caller.</returns>
        /// <inheritdoc cref="SwedishCodeActivity{T}"/>
        protected override object Execute(CodeActivityContext context)
        {
            ITerminalServicesManager iTerminalServicesManager = new TerminalServicesManager();
            StringBuilder            newStringBuilder         = new StringBuilder();

            using (ITerminalServer server = iTerminalServicesManager.GetRemoteServer(Environment.MachineName))
            {
                server.Open();
                IList <ITerminalServicesSession> newSessionsList = server.GetSessions();
                Parallel.ForEach(
                    newSessionsList,
                    s =>
                {
                    if (!string.IsNullOrWhiteSpace(s.UserName))
                    {
                        newStringBuilder.AppendLine($"Session: {s.SessionId} UserName: {s.UserName} LogonTime: {s.LoginTime} IdleTime: {s.IdleTime}");
                    }
                });
            }

            return(newStringBuilder.ToString());
        }
        public PluginOutputCollection Output()
        {
            ITerminalServicesManager  manager = new TerminalServicesManager();
            List <SimplePluginOutput> listSPO = new List <SimplePluginOutput>();

            _pluginOutputs.PluginOutputList.Clear();
            using (ITerminalServer server = manager.GetRemoteServer(Environment.MachineName.ToString()))
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    NTAccount account = session.UserAccount;
                    if (account != null)
                    {
                        listSPO.Add(new SimplePluginOutput(account.ToString(), false));

                        _pluginOutputs.PluginOutputList.Add(new PluginOutput("User", listSPO));
                    }
                }
            }
            return(_pluginOutputs);
        }
 private static void LogoffSession(
     string serverName,
     int sessionId)
 {
     try
     {
         var manager = new TerminalServicesManager();
         using (var server = manager.GetRemoteServer(serverName))
         {
             server.Open();
             var sessionToLogoff = server.GetSessions().Where(session => session.SessionId == sessionId).FirstOrDefault();
             if (sessionToLogoff != null)
             {
                 sessionToLogoff.Logoff(true);
             }
             server.Close();
         }
     }
     catch (Exception exc)
     {
         Trace.TraceError("Failed to logoff session id {0} on server {1} ({2})", sessionId, serverName, exc);
     }
 }
        public static bool ServerIsBusy()
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer(ServerIPAddress))
            {
                server.Open();
                var session = server.GetSessions().Where(x => x.UserName == UserNameOnServer).FirstOrDefault();
                if (session != null)
                {
                    ClientName      = session.ClientName;
                    ClientIPAddress = session.ClientIPAddress?.ToString();
                    IdleTime        = session.IdleTime;

                    ClearMemory();

                    return(session.ConnectionState == ConnectionState.Active);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #14
0
        private ITerminalServicesSession[] GetUsers(string szMachine, string szUsername, CancellationToken _cancel)
        {
            bool _exceptionThrown = false;
            //List<CimInstance> _results = new List<CimInstance>();
            List <ITerminalServicesSession> _results = new List <ITerminalServicesSession>();

            if (!_cancel.IsCancellationRequested)
            {
                try
                {
                    ITerminalServicesManager _tManager = new TerminalServicesManager();

                    using (ITerminalServer _tServer = _tManager.GetRemoteServer(szMachine))
                    {
                        _tServer.Open();
                        foreach (ITerminalServicesSession _sesh in _tServer.GetSessions())
                        {
                            if (_cancel.IsCancellationRequested)
                            {
                                break;
                            }

                            if (_sesh.UserName.ToLower().Contains(szUsername.ToLower()))
                            {
                                _results.Add(_sesh);
                            }
                        }
                    }
                }
                catch (Win32Exception _w32)
                {
                    switch (_w32.HResult)
                    {
                    case unchecked ((int)0x80004005):
                        Status($"Error Gathering Logged On Users ({szMachine}) - most likely offline / firewall");
                        break;

                    default:
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            System.Diagnostics.Debugger.Break();
                        }

                        Status($"Error Gathering Logged On Users ({szMachine}) - PROVIDE TO SUPPORT - W32 UNKNKOWN ({_w32.HResult})");
                        break;
                    }
                    _exceptionThrown = true;
                }
                catch (Exception _ex)
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    Status($"Error Gathering Logged On Users ({szMachine}) - PROVIDE TO SUPPORT - UNKNKOWN ({_ex.GetType().Name}:{_ex.HResult})");
                    _exceptionThrown = true;
                }
                if (_exceptionThrown)
                {
                    _results.Clear();                    // clear results so we do not error and can continue.
                    System.Threading.Thread.Sleep(5000); // give them time to see the error
                }
            }
            return(_results.ToArray());
        }
Exemple #15
0
 public string LogOffUsers()          //Almost exactly the same as the query for logged in users except we log off each session
 {
     try
     {
         ITerminalServicesManager manager = new TerminalServicesManager();
         if (middletier == "All")
         {
             bool result = CautionMessage();
             if (result)
             {
                 foreach (DataRow mt in mtTable.Rows)
                 {
                     ExtractFromTable(mt);
                     using (ITerminalServer server = manager.GetRemoteServer(middletier))
                     {
                         server.Open();
                         foreach (ITerminalServicesSession session in server.GetSessions())
                         {
                             NTAccount account = session.UserAccount;
                             if (account != null)
                             {
                                 session.Logoff();
                                 worker.ReportProgress(0, commandResult = account + " is being logged off of " + middletier + Environment.NewLine);
                             }
                         }
                     }
                 }
                 return(commandResult);
             }
             else
             {
                 return(commandResult);
             }
         }
         else
         {
             bool result = CautionMessage();
             if (result)                      //Dialog result is yes, proceed
             {
                 using (ITerminalServer server = manager.GetRemoteServer(middletier))
                 {
                     server.Open();
                     foreach (ITerminalServicesSession session in server.GetSessions())
                     {
                         NTAccount account = session.UserAccount;
                         if (account != null)
                         {
                             session.Logoff();
                             worker.ReportProgress(0, commandResult = account + " is being logged off of " + middletier + Environment.NewLine);
                         }
                     }
                 }
                 return(commandResult);
             }
             else
             {
                 return(commandResult);
             }
         }
     }
     catch (Exception ex)
     {
         throw new ApplicationException("Application encountered an error while attempting to log users off of middletiers: ", ex);
     }
 }
        protected override void Execute(CodeActivityContext context)
        {
            var serverName = this.ServerName.Get(context);

            Console.WriteLine("Server Name: " + serverName);

            try
            {
                DataTable                serverHealthDataTable = new DataTable();
                string                   serverHealthHtmlTable = string.Empty;
                List <ServerDetail>      serverDetails         = new List <ServerDetail>();
                ITerminalServicesManager manager = new TerminalServicesManager();
                using (ITerminalServer server = manager.GetRemoteServer(serverName))
                {
                    server.Open();
                    foreach (ITerminalServicesSession session in server.GetSessions())
                    {
                        NTAccount account = session.UserAccount;
                        if (account != null)
                        {
                            AddInfo("UserAccount" + " : " + account);
                            AddInfo("\t" + "ServerName" + " : " + session.Server.ServerName);
                            AddInfo("\t" + "UserName" + " : " + session.UserName);
                            AddInfo("\t" + "DomainName" + " : " + session.DomainName);
                            AddInfo("\t" + "WindowStationName" + " : " + session.WindowStationName);

                            AddInfo("\t" + "SessionId" + " : " + session.SessionId);

                            AddInfo("\t" + "CurrentTime" + " : " + session.CurrentTime);
                            AddInfo("\t" + "LoginTime" + " : " + session.LoginTime);
                            AddInfo("\t" + "LastInputTime" + " : " + session.LastInputTime);
                            AddInfo("\t" + "IdleTime" + " : " + session.IdleTime);
                            AddInfo("\t" + "ConnectTime" + " : " + session.ConnectTime);
                            AddInfo("\t" + "DisconnectTime" + " : " + session.DisconnectTime);

                            AddInfo(string.Empty);
                            AddInfo("\t" + "Processes:");

                            foreach (var process in session.GetProcesses())
                            {
                                AddInfo("\t\t" + process.ProcessName);
                            }

                            AddInfo(string.Empty);

                            serverDetails.Add(new ServerDetail(session));
                        }
                    }
                }

                if (serverDetails.Count > 0)
                {
                    serverHealthDataTable = Utility.ListToDataTable <ServerDetail>(serverDetails);
                    serverHealthHtmlTable = Utility.DataTableToHtml(serverHealthDataTable);
                }

                this.ServerHealthDataTable.Set(context, serverHealthDataTable);
                this.ServerHealthHtmlTable.Set(context, serverHealthHtmlTable);
            }
            catch (Exception ex)
            {
                Console.WriteLine("EXCEPTION : " + ex.Message);
            }
        }
Exemple #17
0
 public string LoggedUsers()
 {
     try
     {
         ITerminalServicesManager manager = new TerminalServicesManager();
         if (middletier == "All")
         {
             bool result = CautionMessage();
             if (result)
             {
                 foreach (DataRow mt in mtTable.Rows)
                 {
                     ExtractFromTable(mt);
                     using (ITerminalServer server = manager.GetRemoteServer(middletier))                             //Connects to the remote terminal server requested
                     {
                         server.Open();
                         foreach (ITerminalServicesSession session in server.GetSessions())                                 //Pulls all of the logged in user sessions
                         {
                             NTAccount account = session.UserAccount;
                             if (account != null)
                             {
                                 worker.ReportProgress(0, commandResult = account + " is active on " + middletier + Environment.NewLine);
                             }
                         }
                     }
                 }
                 return(commandResult);
             }
             else
             {
                 return(commandResult);
             }
         }
         else
         {
             bool result = CautionMessage();
             if (result)                      //Dialog result is yes, proceed
             {
                 using (ITerminalServer server = manager.GetRemoteServer(middletier))
                 {
                     server.Open();
                     foreach (ITerminalServicesSession session in server.GetSessions())
                     {
                         NTAccount account = session.UserAccount;
                         if (account != null)
                         {
                             worker.ReportProgress(0, commandResult = account + " is active on " + middletier + Environment.NewLine);
                         }
                     }
                 }
                 return(commandResult);
             }
             else
             {
                 return(commandResult);
             }
         }
     }
     catch (Exception ex)
     {
         throw new ApplicationException("Application encountered an error while attempting to check logged in users: ", ex);
     }
 }