Пример #1
0
 static void CheckBackupTime(object sender, System.Timers.ElapsedEventArgs e)
 {
     if ((int)DateTime.Now.DayOfWeek != Settings.Default.backupday)
     {
         return;
     }
     backupTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, (int)Settings.Default.backuphour, (int)Settings.Default.backupminute, 0);
     if (backupTime > DateTime.Now)
     {
         if ((int)(backupTime - DateTime.Now).TotalMinutes <= Settings.Default.startcheck)
         {
             foreach (var session in activeusers)
             {
                 if (!Notifications.ContainsKey(session.SessionId))
                 {
                     SendMessage(session.SessionId, Settings.Default.alert1box.Replace("{time}", backupTime.ToString("HH:mm")));
                     Notifications.Add(session.SessionId, DateTime.Now);
                 }
                 else
                 {
                     if ((DateTime.Now - Notifications[session.SessionId]).TotalMinutes >= (int)Settings.Default.alert_interval)
                     {
                         SendMessage(session.SessionId, Settings.Default.alert1box.Replace("{time}", backupTime.ToString("HH:mm")));
                         Notifications[session.SessionId] = DateTime.Now;
                     }
                 }
             }
         }
     }
     else
     {
         if (backupTime < startuptime)
         {
             FinishedBackups.Add(backupTime);
             return;
         }
         if (!FinishedBackups.Contains(backupTime))
         {
             ITerminalServicesManager manager = new TerminalServicesManager();
             using (ITerminalServer server = manager.GetLocalServer())
             {
                 server.Open();
                 foreach (ITerminalServicesSession session in server.GetSessions())
                 {
                     KillParusWithNotifiction(session);
                 }
             }
             if (Settings.Default.backupauto && Application.OpenForms.OfType <BackupWindow>().Count() == 0)
             {
                 bwindow = new BackupWindow();
                 bwindow.ShowDialog();
             }
         }
     }
 }
Пример #2
0
 /// <summary>
 /// Register all active sessions on server(s)
 /// </summary>
 public void RegisterSessions()
 {
     if (!checkProgramActivityTimer.Enabled)
     {
         checkProgramActivityTimer.Start();
     }
     if (!troubleShootingTimer.Enabled)
     {
         troubleShootingTimer.Start();
     }
     activeSessions = new List <ActiveSession>();
     for (int i = LogonTracerConfig.Instance.ServersToTrace.Count() - 1; i > -1; i--)
     {
         string serverName = LogonTracerConfig.Instance.ServersToTrace[i];
         try
         {
             using (ITerminalServer server = manager.GetRemoteServer(serverName))
             {
                 server.Open();
                 foreach (ITerminalServicesSession session in server.GetSessions())
                 {
                     ActiveSession activeSession = null;
                     if (session.UserAccount == null || session.ConnectionState != Cassia.ConnectionState.Active)
                     {
                         continue;
                     }
                     activeSession = repoProvider.BuildSession(session);
                     activeSessions.Add(activeSession);
                     if (activeSession.DbId.HasValue && LogonTracerConfig.Instance.LogSessionHistory)
                     {
                         repoProvider.UpdateSessionHistory(activeSession.DbId.Value, SessionUpdateDetails.StateUpdated, new Dictionary <string, string>
                         {
                             { "Old value", SessionState.ServiceDown.ToString() },
                             { "New value", SessionState.Active.ToString() }
                         });
                     }
                     repoProvider.SaveSession(activeSession);
                 }
             }
         }
         catch (Win32Exception ex)
         {
             LoggingUtils.DefaultLogger.AddLogMessage(this, MessageType.Error, "Error while trying access the server. Check Remote Desktop Services Permissions for this server and try again. Server:{0}. Message: {1}", serverName, ex.Message);
             LogonTracerConfig.Instance.ServersToTrace = LogonTracerConfig.Instance.ServersToTrace.Where(stt => stt != serverName).ToArray();
         }
         catch (Exception ex)
         {
             LoggingUtils.DefaultLogger.AddLogMessage(this, MessageType.Error, "Type: {0}. Server:{1}. Message: {2}", ex.GetType(), serverName, ex.Message);
         }
     }
     inputActivityTimer.Start();
     sessionStateUpdateTimer.Start();
     checkRepositoryTimer.Start();
 }
Пример #3
0
 private static void ListProcesses(string[] args)
 {
     if (args.Length < 2)
     {
         Console.WriteLine("Usage: SessionInfo listprocesses [server]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         WriteProcesses(server.GetProcesses());
     }
 }
Пример #4
0
 private void initServer()
 {
     try
     {
         ITerminalServicesManager manager = new TerminalServicesManager();
         server = manager.GetLocalServer();
         server.Open();
     }
     catch (Exception)
     {
         Console.WriteLine("[Error] no se ha podido identificar el terminal server.");
     }
 }
Пример #5
0
 private static void Shutdown(string[] args)
 {
     if (args.Length < 3)
     {
         Console.WriteLine("Usage: SessionInfo shutdown [server] [shutdown type]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         ShutdownType type = (ShutdownType)Enum.Parse(typeof(ShutdownType), args[2], true);
         server.Shutdown(type);
     }
 }
Пример #6
0
 /// <summary>
 /// Logouts all currently s
 /// </summary>
 public static void LogoutUsers()
 {
     using (ITerminalServer server = _manager.GetLocalServer())
     {
         server.Open();
         foreach (ITerminalServicesSession session in server.GetSessions())
         {
             if (session.SessionId != 0)
             {
                 session.Logoff();
             }
         }
     }
 }
Пример #7
0
 public static void LogOffSession(ITerminalServer Server, int sessionID)
 {
     using (ITerminalServer server = Server)
     {
         server.Open();
         ITerminalServicesSession session = server.GetSession(sessionID);
         session.Logoff(false);
         server.Close();
         MessageBox.Show(new Form()
         {
             TopMost = true
         }, "Wysłano instrukcję wyłączenia sesji", "Rozłączanie sesji", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Пример #8
0
        private static void GetSessionInfo(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo get [server] [session id]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                WriteSessionInfo(server.GetSession(sessionId));
            }
        }
Пример #9
0
 private static void ListSessions(string[] args)
 {
     if (args.Length < 2)
     {
         Console.WriteLine("Usage: SessionInfo listsessions [server]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         foreach (ITerminalServicesSession session in server.GetSessions())
         {
             WriteSessionInfo(session);
         }
     }
 }
Пример #10
0
        private static void ListSessionProcesses(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo listsessionprocesses [server] [session id]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                WriteProcesses(session.GetProcesses());
            }
        }
Пример #11
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;
            }
        }
Пример #12
0
        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);
                    }
                }
            }
        }
        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);
        }
Пример #14
0
        private static void DisconnectSession(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo disconnect [server] [session id]");
                return;
            }
            string serverName = args[1];
            int    sessionId  = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(serverName))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                session.Disconnect();
            }
        }
Пример #15
0
        private static void KillProcess(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("Usage: SessionInfo killprocess [server] [process id] [exit code]");
                return;
            }
            int processId = int.Parse(args[2]);
            int exitCode  = int.Parse(args[3]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesProcess process = server.GetProcess(processId);
                process.Kill(exitCode);
            }
        }
Пример #16
0
        public static void SendMessage(int sessionid, string message)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetLocalServer())
            {
                server.Open();
                try
                {
                    var session = server.GetSession(sessionid);
                    session.MessageBox(message, "Сообщение");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка отправки сообщения: " + ex.Message);
                }
            }
        }
Пример #17
0
        private static void SendMessage(string[] args)
        {
            if (args.Length < 6)
            {
                Console.WriteLine("Usage: SessionInfo message [server] [session id] [icon] [caption] [text]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                RemoteMessageBoxIcon     icon    =
                    (RemoteMessageBoxIcon)Enum.Parse(typeof(RemoteMessageBoxIcon), args[3], true);
                session.MessageBox(args[5], args[4], icon);
            }
        }
Пример #18
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);
        }
Пример #19
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();
        }
Пример #20
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);
        }
Пример #21
0
        static void Main(string[] args)
        {
            using (ITerminalServer server = manager.GetLocalServer()) {
                server.Open();

                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    if (session.UserAccount == null || session.SessionId == 0)
                    {
                        continue; // Don't touch system session
                    }
                    if (session.SessionId == manager.CurrentSession.SessionId)
                    {
                        continue; // Don't touch current session
                    }

                    session.Logoff();
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Find session among all servers and sessions
        /// </summary>
        /// <param name="activeSession">Registered session</param>
        /// <returns>Session</returns>
        private ITerminalServicesSession FindSession(ActiveSession activeSession)
        {
            ITerminalServicesSession foundedSession = null;

            foreach (string serverName in LogonTracerConfig.Instance.ServersToTrace)
            {
                try
                {
                    using (ITerminalServer server = manager.GetRemoteServer(serverName))
                    {
                        server.Open();
                        foreach (ITerminalServicesSession session in server.GetSessions())
                        {
                            if (session.UserAccount == null)
                            {
                                continue;
                            }
                            if (activeSessions.Where(acs => acs.MachineName == session.Server.ServerName &&
                                                     acs.UserName == session.UserName &&
                                                     /*AppData.DateTimeConvertUtils.Compare(acs.SessionBegin.Value, session.ConnectTime.Value) == 1*/ acs.SessionBegin.Value == session.ConnectTime.Value).Count() == 0 &&
                                session.ConnectionState != Cassia.ConnectionState.Disconnected)
                            {
                                ActiveSession newSession = repoProvider.BuildSession(session);
                                activeSessions.Add(newSession);
                                repoProvider.SaveSession(newSession);
                                continue;
                            }
                            if (session.UserName == activeSession.UserName && session.Server.ServerName == activeSession.MachineName)
                            {
                                foundedSession = session;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingUtils.DefaultLogger.AddLogMessage(this, MessageType.Error, "Type: {0}. Server{1}. Message: {2}", ex.GetType(), serverName, ex.Message);
                }
            }
            return(foundedSession);
        }
Пример #23
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);
        }
Пример #25
0
        static void UpdateUsers(object sender, System.Timers.ElapsedEventArgs e)
        {
            activeusers.Clear();
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetLocalServer())
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    if (ParusRunned(session.GetProcesses()))
                    {
                        activeusers.Add(session);
                    }
                }
            }
            if (uwindow != null)
            {
                try { uwindow.UpdateList(); }
                catch { }
            }
        }
        public Response DropUserSession([FromBody] string username)
        {
            var response = new Response();

            try
            {
                Log.Debug($"DropUserSession called for user {username}.");

                var manager = new TerminalServicesManager();
                using (ITerminalServer server = manager.GetLocalServer())
                {
                    server.Open();
                    var userSession = server.GetSessions()
                                      .FirstOrDefault(s => string.Equals($@"{s.DomainName}\{s.UserName}", username, StringComparison.InvariantCultureIgnoreCase));

                    if (userSession == null)
                    {
                        response.Status = Status.Error;
                        response.AddErrorNotification($"User session for {username} not found.");
                        return(response);
                    }

                    userSession.Logoff(true);
                }

                var message = $"Successfully closed session for user {username}.";
                Log.Debug(message);
                response.AddSuccessNotification(message);
                return(response);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                response.Status = Status.Error;
                response.AddErrorNotification(ex.Message, ex.StackTrace);
                return(response);
            }
        }
Пример #27
0
        static void LogUserOut(string computerId)
        {
            using (ITerminalServer server = manager.GetRemoteServer(computerId))
            {
                if (!server.IsOpen) // check to see if RPC is enabled.
                {
                    return;
                }

                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    // Example snipit
                    //Console.WriteLine("Hi there, " + session.UserAccount + " on session " + session.SessionId);
                    //Console.WriteLine("It looks like you logged on at " + session.LoginTime + " and are now " + session.ConnectionState);

                    if (server.IsOpen)                   // check if server is up
                    {
                        if (session.UserAccount != null) // skip any windows accounts
                        {
                            try                          // try to disconnect sessions
                            {
                                session.Disconnect();
                                Console.WriteLine("Logged the user out.");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("General failure.");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Could not ping server.");
                    }
                }
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetLocalServer())
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    //Console.WriteLine(session.UserAccount.Value);
                    if (session.UserName == Environment.UserName)
                    {
                        Console.WriteLine(session.UserAccount + " on session " + session.SessionId + " ip address " + session.ClientIPAddress);



                        //Console.WriteLine("It looks like you logged on at " + session.LoginTime + " and are now " + session.ConnectionState);
                    }
                }
            }

            Console.ReadKey();
        }
        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);
                }
            }
        }
Пример #30
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());
        }