public static List <ITerminalServicesSession> GetList() { List <ITerminalServicesSession> session_list = new List <ITerminalServicesSession>(); ITerminalServicesManager manager = new TerminalServicesManager(); using (ITerminalServer server = manager.GetLocalServer()) { server.Open(); foreach (ITerminalServicesSession session in server.GetSessions()) { // skip the SYSTEM session if (session.SessionId == 0) { continue; } // if there is no username the session is special accounts if (session.UserName == String.Empty) { continue; } session_list.Add(session); } } return(session_list); }
public Response GetUserSesssions() { var response = new Response(); try { var manager = new TerminalServicesManager(); using (ITerminalServer server = manager.GetLocalServer()) { server.Open(); var sessions = server.GetSessions() .Where(s => !string.IsNullOrEmpty(s.UserName)) .Select(s => new { User = s.DomainName + @"\" + s.UserName, LoginDate = s.LoginTime?.ToString("g"), State = s.ConnectionState.ToString() }); response.Data = sessions; return(response); } } catch (Exception ex) { Log.Error(ex.Message); response.Status = Status.Error; response.Notifications.Add(new Notification { Message = ex.Message, MessageDetail = ex.StackTrace, Status = Status.Error }); return(response); } }
private static int GetUserSessionId(string username) { try { ITerminalServicesManager manager = new TerminalServicesManager(); using (ITerminalServer server = manager.GetLocalServer()) { server.Open(); foreach (ITerminalServicesSession session in server.GetSessions()) { NTAccount account = session.UserAccount; if (account == null) { continue; } var userName = account.Value.Split('\\')[1]; if (userName.ToLower().Equals(username.ToLower())) { return(session.SessionId); } } } return(-1); } catch (Exception) { return(-1); } }
private void ValidateSessionsAsync() { ThreadPool.QueueUserWorkItem(async(object o) => { ITerminalServicesManager manager = new TerminalServicesManager(); using (ITerminalServer server = manager.GetLocalServer()) { server.Open(); var localSessions = server.GetSessions().Where(s => s.SessionId > 0 && (s.ConnectionState == Cassia.ConnectionState.Active)); var messages = await _msgReader.GetAllMessages(); if (messages.Count(m => m.Command.Type == WinGuard.Domain.Enumaretions.ClientCommandType.LOGOUT) > 0 && localSessions.Any(s => messages.Any(m => m.Command.ClientIdentifier == s.SessionId.ToString()))) { foreach (var session in localSessions.Where(s => messages.Any(m => m.Command.ClientIdentifier == s.SessionId.ToString()))) { session.Logoff(); } return; } foreach (ITerminalServicesSession session in localSessions) { await _authService.Login(_encryptService.EncryptMessage(session.SessionId.ToString()), _encryptService.EncryptMessage(session.UserName)); } } }); }
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(); } } } }
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."); } }
private ITerminalServer GetServer() { var mgr = new TerminalServicesManager(); if (string.IsNullOrWhiteSpace(ComputerName)) { // Local Machine return(mgr.GetLocalServer()); } else { // Remote Machine return(mgr.GetRemoteServer(ComputerName)); } }
ITerminalServicesSession TryGetSession(int sessionID) { try { var manager = new TerminalServicesManager(); using (var server = manager.GetLocalServer()) { return(server.GetSession(sessionID)); } } catch (Exception exception) { Program.Trace($"Unable to get terminalServicesSession: { exception.Message }"); } return(null); }
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); } } }
private void TryEnumerateSessions() { try { Program.Trace("Enumerating sessions"); var manager = new TerminalServicesManager(); using (var server = manager.GetLocalServer()) { foreach (var session in server.GetSessions()) { if (session == null) { continue; // Doubt this ever happens, but just to be sure } // For debug purposes string userID = ""; if (!string.IsNullOrWhiteSpace(session.UserName) || !string.IsNullOrEmpty(session.UserAccount?.ToString())) { userID = $" (UserName: { session.UserName }, NTAccount: { session.UserAccount })"; } Program.Trace($"Session { session.SessionId }{ userID }: { session.ConnectionState }"); // Start a logger in that session Task startLogger; if (!UnqualifiedConnectionStates.Contains(session.ConnectionState)) { startLogger = TryRunLoggerInSessionAsync(session); } } } } catch (Exception exception) { Program.Trace($"Error when enumerating sessions: { exception.Message }"); } }
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); } }
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 ITerminalServicesSession GetActiveSession() { ITerminalServicesSession activeSession = null; var manager = new TerminalServicesManager(); if (manager != null) { using (var server = manager.GetLocalServer()) { server.Open(); foreach (var session in server.GetSessions()) { if (session.ConnectionState == ConnectionState.Active) { activeSession = session; break; } } } } return(activeSession); }
/// <summary>Returns the process of the running logger instance in the given session, returns null if none was found</summary> Process TryFindRunningLoggerInstance(int sessionID) { try { var manager = new TerminalServicesManager(); using (var server = manager.GetLocalServer()) { foreach (var process in server.GetProcesses()) { if (process.SessionId != sessionID) // Skip processes of other sessions { continue; } var fileName = process.UnderlyingProcess.TryGetFileName(); // Compare filename, if match we found a running instance if (fileName != null && Program.NormalizePath(fileName) == Program.InstallLocationNormalized) { return(process.UnderlyingProcess); } } } } catch (Win32Exception exception) when(exception.NativeErrorCode == WinAPI.ERROR_UNKNOWN && sessionID == 0) { // As expected } catch (Exception exception) { Program.Trace($"Exception when enumerating processes: { exception.GetType() }: { exception.Message }"); } return(null); }
private void BackgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { stopWatch = new Stopwatch(); stopWatch.Start(); stoped = false; BeginInvoke((Action)(() => { LogOutput.AppendText("Проверка пользователей..."); })); ITerminalServicesManager manager = new TerminalServicesManager(); using (ITerminalServer server = manager.GetLocalServer()) { try { Dictionary <string, List <ITerminalServicesProcess> > users = new Dictionary <string, List <ITerminalServicesProcess> >(); server.Open(); foreach (var session in server.GetSessions()) { List <ITerminalServicesProcess> pr = new List <ITerminalServicesProcess>(); var processes = session.GetProcesses(); foreach (var l in processes) { if (Program.IsParus(l)) { pr.Add(l); } } if (pr.Count > 0) { users.Add(session.UserName, pr); } } if (users.Count > 0) { string text = String.Empty; foreach (var u in users) { if (String.IsNullOrEmpty(text)) { text = u.Key; } else { text += Environment.NewLine + u.Key; } } var result = AutoClosingMessageBox.Show(text, "Закрыть все активные соединения?", 60000, MessageBoxButtons.YesNo, DialogResult.Yes); if (result == DialogResult.Yes) { foreach (var u in users) { foreach (var proc in u.Value) { proc.Kill(); } } BeginInvoke((Action)(() => { LogOutput.AppendText(Environment.NewLine + "Закрытые пользователи:" + Environment.NewLine + text); })); } } } catch (Exception ex) { BeginInvoke((Action)(() => { LogOutput.AppendText(Environment.NewLine + "Ошибка проверки пользователей:" + ex.Message); })); } } _totalFileCount = 0; foreach (var path in Program.dirs) { _totalFileCount += FolderContentsCount(path); } BeginInvoke((Action)(() => { LogOutput.AppendText(Environment.NewLine + "Создание бэкапа базы данных Parus " + DateTime.Now.ToString("dd/MM/yyyy HH:mm")); LogOutput.AppendText(Environment.NewLine + "Общее количество папок: " + Program.dirs.Count); LogOutput.AppendText(Environment.NewLine + "Общее количество файлов: " + _totalFileCount); })); FastZipEvents events = new FastZipEvents(); ZipStrings.CodePage = 866; events.ProcessFile = ProcessFileMethod; FastZip fastZip = new FastZip(events) { CreateEmptyDirectories = true }; datefolder = "ParusBackup " + DateTime.Now.ToString("dd-MM-yyyy-HH-mm"); if (!Directory.Exists(Properties.Settings.Default.savepath + "\\" + datefolder)) { Directory.CreateDirectory(Properties.Settings.Default.savepath + "\\" + datefolder); } foreach (var path in Program.dirs) { try { var dp = path.Split('\\'); string zipFileName = Properties.Settings.Default.savepath + "\\" + datefolder + "\\" + ((dp.Count() >= 2) ? dp[dp.Count() - 2] + "." + dp[dp.Count() - 1] : dp.Last()) + ".zip"; fastZip.CreateZip(zipFileName, path, true, ""); BeginInvoke((Action)(() => { LogOutput.AppendText(Environment.NewLine + "Выполнена архивация папки " + path); })); } catch (Exception ex) { BeginInvoke((Action)(() => { LogOutput.AppendText(Environment.NewLine + "Ошибка архивации папки " + path + ": " + ex.Message); })); } } stopWatch.Stop(); }