private static void AskQuestion(string[] args) { if (args.Length < 8) { Console.WriteLine( "Usage: SessionInfo ask [server] [session id] [icon] [caption] [text] [timeout] [buttons]"); return; } int seconds = int.Parse(args[6]); 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); RemoteMessageBoxButtons buttons = (RemoteMessageBoxButtons)Enum.Parse(typeof(RemoteMessageBoxButtons), args[7], true); RemoteMessageBoxResult result = session.MessageBox(args[5], args[4], buttons, icon, default(RemoteMessageBoxDefaultButton), default(RemoteMessageBoxOptions), TimeSpan.FromSeconds(seconds), true); Console.WriteLine("Response: " + result); } }
protected override void OnPowerChange(PowerChangeEvent e) { ITerminalServicesSession consoleSession = this[null]; string clientUser = consoleSession.GetClientUser(); if (Context.DebugLog) { var sb = new StringBuilder(); sb.Append($"PowerEvent: Status={e.Status} "); sb.Append("("); sb.Append($"Console: SessionId={consoleSession.SessionId}, "); if (clientUser.Length > 0) { sb.Append($"User={clientUser}, "); } sb.Append($"State={consoleSession.ConnectionState}"); if (consoleSession.ConnectionState == Cassia.ConnectionState.Active) { sb.Append($"|{(ConsoleLocked ? "Locked" : "Unlocked")}"); } sb.Append(")"); EventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information, 90); } }
Task TryRunLoggerInSessionAsync(ITerminalServicesSession session) { if (session == null) { throw new ArgumentNullException(nameof(session)); } return(TryRunLoggerInSessionAsync(session.SessionId, session.UserAccount?.ToString())); }
protected override void OnSessionChange(SessionChangeEvent e) { SessionChangeDescription desc = e.Description; ITerminalServicesSession session = wtsServer.GetSession(desc.SessionId); ITerminalServicesSession consoleSession = wtsServer.GetConsoleSession(); string clientUser = session.GetClientUser(); if (Context.DebugLog) { var sb = new StringBuilder(); sb.Append($"SessionChange: SessionId={desc.SessionId}, Reason={desc.Reason}"); sb.Append("("); if (clientUser.Length > 0) { sb.Append($"User={clientUser}, "); } sb.Append($"State={session.ConnectionState}"); sb.Append(")"); EventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information, 91); } if (session.SessionId == consoleSession.SessionId) { if (desc.Reason == SessionChangeReason.SessionLock) { ConsoleLocked = true; } else if (desc.Reason == SessionChangeReason.SessionUnlock) { ConsoleLocked = false; } } if (desc.Reason == SessionChangeReason.SessionLogon || desc.Reason == SessionChangeReason.SessionUnlock && !session.IsRemoteConnected() || desc.Reason == SessionChangeReason.ConsoleConnect || desc.Reason == SessionChangeReason.RemoteConnect) { if (session.ConnectionState == ConnectionState.Active) { if (Context.EventLog) { EventLog.WriteEntry($"User login: {clientUser}", EventLogEntryType.Information, 1); } UserLogin?.Invoke(this, new UserLoginEventArgs { Session = session }); } } }
private static void WriteSessionInfo(ITerminalServicesSession session) { if (session == null) { return; } Console.WriteLine("Session ID: " + session.SessionId); if (session.UserAccount != null) { Console.WriteLine("User: "******"IP Address: " + session.ClientIPAddress); } if (session.RemoteEndPoint != null) { Console.WriteLine("Remote endpoint: " + session.RemoteEndPoint); } Console.WriteLine("Window Station: " + session.WindowStationName); Console.WriteLine("Client Directory: " + session.ClientDirectory); Console.WriteLine("Client Build Number: " + session.ClientBuildNumber); Console.WriteLine("Client Hardware ID: " + session.ClientHardwareId); Console.WriteLine("Client Product ID: " + session.ClientProductId); Console.WriteLine("Client Protocol Type: " + session.ClientProtocolType); if (session.ClientProtocolType != ClientProtocolType.Console) { // These properties often throw exceptions for the console session. Console.WriteLine("Application Name: " + session.ApplicationName); Console.WriteLine("Initial Program: " + session.InitialProgram); Console.WriteLine("Initial Working Directory: " + session.WorkingDirectory); } Console.WriteLine("State: " + session.ConnectionState); Console.WriteLine("Connect Time: " + session.ConnectTime); Console.WriteLine("Logon Time: " + session.LoginTime); Console.WriteLine("Last Input Time: " + session.LastInputTime); Console.WriteLine("Idle Time: " + session.IdleTime); Console.WriteLine(string.Format("Client Display: {0}x{1} with {2} bits per pixel", session.ClientDisplay.HorizontalResolution, session.ClientDisplay.VerticalResolution, session.ClientDisplay.BitsPerPixel)); if (session.IncomingStatistics != null) { Console.Write("Incoming protocol statistics: "); WriteProtocolStatistics(session.IncomingStatistics); Console.WriteLine(); } if (session.OutgoingStatistics != null) { Console.Write("Outgoing protocol statistics: "); WriteProtocolStatistics(session.OutgoingStatistics); Console.WriteLine(); } Console.WriteLine(); }
public static string GetClientUser(this ITerminalServicesSession session) { string user = session.ClientName; if (session.ClientName.Length > 0 && session.UserName.Length > 0) { user += "\\"; } user += session.UserName; return(user); }
private void OnInputActivityTimer(object sender, System.Timers.ElapsedEventArgs args) { #if DEBUG if (sessionLocked) { return; } #endif sessionLocked = true; if (activeSessions.Count == 0) { RegisterSessions(); sessionLocked = false; return; } for (int i = 0; i < activeSessions.Count; i++) { bool activityRegistered = false; ActiveSession activeSession = activeSessions[i]; ITerminalServicesSession session = FindSession(activeSession); if (session != null) { if (AppData.DateTimeConvertUtils.Compare(activeSession.LastInputTime, session.LastInputTime) != 1 && (AppData.DateTimeConvertUtils.ConvertTimeByUtcOffset(DateTime.Now, LogonTracerConfig.Instance.UtcOffset).Value - AppData.DateTimeConvertUtils.ConvertTimeByUtcOffset(session.ConnectTime, LogonTracerConfig.Instance.UtcOffset).Value).TotalMinutes > LogonTracerConfig.Instance.InputActivityTimePeriod) { Dictionary <string, string> activeHoursDict = new Dictionary <string, string> { { "Old value", activeSession.ActivityHours.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) } }; Dictionary <string, string> lastInputTimeDict = new Dictionary <string, string> { { "Old value", activeSession.LastInputTime.ToString() } }; activeSession.ActivityHours += Convert.ToDouble(LogonTracerConfig.Instance.InputActivityTimePeriod) / 60; activeSession.LastInputTime = session.LastInputTime; activeHoursDict.Add("New value", activeSession.ActivityHours.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture)); lastInputTimeDict.Add("New value", activeSession.LastInputTime.ToString()); activityRegistered = true; if (LogonTracerConfig.Instance.LogSessionHistory) { repoProvider.UpdateSessionHistory(activeSession.DbId.Value, SessionUpdateDetails.ActivityHoursIncreased, activeHoursDict); repoProvider.UpdateSessionHistory(activeSession.DbId.Value, SessionUpdateDetails.LastInputTimeUpdate, lastInputTimeDict); } repoProvider.SaveSession(activeSession); } repoProvider.SaveSessionActivityProfile(activeSession.DbId, activityRegistered); } } UpdateListenersStatus(); sessionLocked = false; }
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); } }
private void OnSessionStateUpdateTimer(object sender, System.Timers.ElapsedEventArgs e) { if (sessionLocked) { return; } sessionLocked = true; for (int i = activeSessions.Count - 1; i > -1; i--) { bool sessionExist = false; ActiveSession activeSession = activeSessions[i]; ITerminalServicesSession session = FindSession(activeSession); if (session != null) { if (/*AppData.DateTimeConvertUtils.Compare(activeSession.SessionBegin.Value, session.ConnectTime.Value) != 1*/ activeSession.SessionBegin.Value != session.ConnectTime.Value) { activeSession.SessionState = SessionState.Disconnected; } if (session.ConnectionState == Cassia.ConnectionState.Disconnected) { activeSession.SessionEnd = session.DisconnectTime; activeSession.SessionState = SessionState.Disconnected; } sessionExist = true; } if (!sessionExist) { activeSession.SessionState = SessionState.Disconnected; } if (activeSession.SessionState != SessionState.Active) { repoProvider.SaveSession(activeSession); if (LogonTracerConfig.Instance.LogSessionHistory) { repoProvider.UpdateSessionHistory(activeSession.DbId.Value, SessionUpdateDetails.StateUpdated, new Dictionary <string, string> { { "Old value", SessionState.Active.ToString() }, { "New value", SessionState.Disconnected.ToString() } }); } activeSessions.Remove(activeSession); } } sessionLocked = false; }
public string ActiveSession(string TermServerName, string SearchedLogin) { System.Text.StringBuilder data = new System.Text.StringBuilder(); var session = new Explorer().FindSession(new Explorer().GetRemoteServer(TermServerName), SearchedLogin); if (session != null) { data.Append(TermServerName + " --------------------------------\n"); data.Append("Nazwa użytkownika Nazwa Sesji IP klienta Id Status Czas bezczynności Czas logowania\n"); SessionIDServer = (session); data.Append(new Explorer().FormatedSession(session)); } return(data.ToString()); }
public void Connect(ITerminalServicesSession target, string password, bool synchronous) { if (!Local) { throw new InvalidOperationException("Cannot connect sessions that are running on remote servers"); } if (IsVistaSp1OrHigher) { WIN32.NativeMethodsHelper.Connect(_sessionId, target.SessionId, password, synchronous); } else { WIN32.NativeMethodsHelper.LegacyConnect(_server.Handle, _sessionId, target.SessionId, password, synchronous); } }
private void RefreshProcesses(object sender, ITerminalServer server, ITerminalServicesSession session, int selectedSessionID) { var tabPage = tabControl.SelectedTab; var dataGridView = (DataGridView)tabPage.Controls.Find("DataGridView", true)[0]; dataGridView.Rows.Clear(); foreach (ITerminalServicesProcess process in new PuzzelLibrary.Terminal.Explorer().GetExplorerProcess(server)) { if (process.SessionId == selectedSessionID) { dataGridView.Rows.Add(session.Server.ServerName, session.UserName, session.WindowStationName, process.SessionId, process.ProcessId, process.ProcessName); } } labelSessionCount.Text = "Lista procesów: " + dataGridView.Rows.Count; }
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()); } }
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(); } }
public static SafeAccessTokenHandle GetToken(this ITerminalServicesSession session) { if (!NativeMethods.WTSQueryUserToken((uint)session.SessionId, out var impersonationToken)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } using (var safeToken = new SafeAccessTokenHandle(impersonationToken)) { if (!NativeMethods.DuplicateTokenEx(safeToken.DangerousGetHandle(), 0, IntPtr.Zero, NativeMethods.ImpersonationLevel.Impersonation, NativeMethods.TokenType.Primary, out var primaryToken)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } return(new SafeAccessTokenHandle(primaryToken)); } }
static void KillParusWithNotifiction(ITerminalServicesSession session) { int kills = 0; foreach (var l in session.GetProcesses()) { if (IsParus(l)) { l.Kill(); kills++; } } if (kills > 0) { SendMessage(session.SessionId, Settings.Default.alert2box.Replace("{time}", DateTime.Now.AddSeconds(secondsleft * 3).ToString("HH:mm"))); } }
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); } }
public int GetLatestSessionId() { ITerminalServicesSession latest = null; foreach (ITerminalServicesSession session in _manager.GetLocalServer().GetSessions()) { if (latest == null || latest.ConnectTime == null || (session.ConnectTime != null && session.ConnectTime > latest.ConnectTime)) { latest = session; } } if (latest == null) { throw new InvalidOperationException("No connected sessions found"); } return(latest.SessionId); }
public ActiveSession BuildSession(ITerminalServicesSession session) { ActiveSession activeSession = new ActiveSession { UserName = session.UserName, MachineName = session.Server.ServerName, SessionBegin = session.ConnectTime.Value, ClientUtcOffset = Convert.ToDouble(TimeZone.CurrentTimeZone.GetUtcOffset(session.ConnectTime.Value).Hours), ClientName = session.ClientName, ClientDisplayDetails = string.Format("Horizontal rezolution: {0}, Vertical rezolution: {1}, Bits per px: {2}", session.ClientDisplay.HorizontalResolution, session.ClientDisplay.VerticalResolution, session.ClientDisplay.BitsPerPixel), ClientReportedIPAddress = session.ClientIPAddress == null ? null : session.ClientIPAddress.ToString(), ClientBuildNumber = session.ClientBuildNumber, SessionState = LogonTracerWorker.SessionState.Active }; logonAdministrationWorker.RegisterNewUser(session.UserName); return(CheckSessionRepositoryExisting(activeSession)); }
/// <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); }
private void refreshProcessTable() { this.tableProcess = new List <TableProces>(); this.process = AdminTools.getComputerProcess(this.computerName); ITerminalServer server = process[0].Server; foreach (ITerminalServicesProcess proc in process) { ITerminalServicesSession session = server.GetSession(proc.SessionId); if (showAllProcess | session.UserAccount != null) { TableProces tmpProc = new TableProces( proc.ProcessId, proc.ProcessName, session.UserName ); tableProcess.Add(tmpProc); } } tableProcess.Sort((x, y) => x.processName.CompareTo(y.processName)); //process_dataGridView.Refresh(); process_dataGridView.DataSource = this.tableProcess; }
private static void WriteSessionInfo(ITerminalServicesSession session) { Console.WriteLine("Session ID: " + session.SessionId); if (session.UserAccount != null) { Console.WriteLine("User: "******"IP Address: " + session.ClientIPAddress); } Console.WriteLine("Window Station: " + session.WindowStationName); Console.WriteLine("Client Build Number: " + session.ClientBuildNumber); Console.WriteLine("State: " + session.ConnectionState); Console.WriteLine("Connect Time: " + session.ConnectTime); Console.WriteLine("Logon Time: " + session.LoginTime); Console.WriteLine("Idle Time: " + session.IdleTime); Console.WriteLine( string.Format("Client Display: {0}x{1} with {2} bits per pixel", session.ClientDisplay.HorizontalResolution, session.ClientDisplay.VerticalResolution, session.ClientDisplay.BitsPerPixel)); Console.WriteLine(); }
public ServerDetail(ITerminalServicesSession session) { this.CurrentTime = session.CurrentTime.ToString(); this.Server = session.Server.ServerName; this.WindowStationName = session.WindowStationName; this.UserAccount = session.UserAccount.ToString(); this.DomainName = session.DomainName; this.UserName = session.UserName; this.SessionId = session.SessionId.ToString(); this.IdleTime = session.IdleTime.ToString(); this.LoginTime = session.LoginTime.ToString(); this.LastInputTime = session.LastInputTime.ToString(); this.DisconnectTime = session.DisconnectTime.ToString(); this.ConnectTime = session.ConnectTime.ToString(); this.ClientName = session.ClientName; this.ClientBuildNumber = session.ClientBuildNumber.ToString(); foreach (var process in session.GetProcesses()) { this.Process += process.ProcessName; this.Process += "\n"; } }
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); }
private static void WriteSessionInfo(ITerminalServicesSession session) { if (session == null) { return; } Console.WriteLine(Lang.SessionID, session.SessionId); if (session.UserAccount != null) { Console.WriteLine(Lang.User, session.UserAccount); } if (session.ClientIPAddress != null) { Console.WriteLine(Lang.IPAddress, session.ClientIPAddress); } if (session.RemoteEndPoint != null) { Console.WriteLine(Lang.RemoteEndpoint + session.RemoteEndPoint); } Console.WriteLine(Lang.WindowStation, session.WindowStationName); Console.WriteLine(Lang.ClientDirectory, session.ClientDirectory); Console.WriteLine(Lang.ClientBuildNumber, session.ClientBuildNumber); Console.WriteLine(Lang.ClientHardwareID, session.ClientHardwareId); Console.WriteLine(Lang.ClientProductID, session.ClientProductId); Console.WriteLine(Lang.ClientProtocolType, session.ClientProtocolType); if (session.ClientProtocolType != ClientProtocolType.Console) { // These properties often throw exceptions for the console session. Console.WriteLine(Lang.ApplicationName, session.ApplicationName); Console.WriteLine(Lang.InitialProgram, session.InitialProgram); Console.WriteLine(Lang.InitialWorkingDirectory, session.WorkingDirectory); } Console.WriteLine(Lang.State, session.ConnectionState); Console.WriteLine(Lang.ConnectTime, session.ConnectTime); Console.WriteLine(Lang.LogonTime, session.LoginTime); Console.WriteLine(Lang.LastInputTime, session.LastInputTime); Console.WriteLine(Lang.IdleTime, session.IdleTime); // show Client Display: {0}x{1} with {2} bits per pixel Console.WriteLine(Lang.ClientDisplay, session.ClientDisplay.HorizontalResolution, session.ClientDisplay.VerticalResolution, session.ClientDisplay.BitsPerPixel); if (session.IncomingStatistics != null) { Console.Write(Lang.IncomingProtocolStatistics); WriteProtocolStatistics(session.IncomingStatistics); Console.WriteLine(); } if (session.OutgoingStatistics != null) { Console.Write(Lang.OutgoingProtocolStatistics); WriteProtocolStatistics(session.OutgoingStatistics); Console.WriteLine(); } Console.WriteLine(); }
private void ContextMenus(object sender, EventArgs e) { int selectedSessionID = 0; DataGridView datagridview = null; int selectedRowIndex = 0; if (tabControl.SelectedTab.Name != "dynaStatusTab") { var tabpage = tabControl.SelectedTab; datagridview = (DataGridView)tabpage.Controls.Find("DataGridView", true)[0]; selectedRowIndex = datagridview.SelectedRows[0].Index; selectedSessionID = Convert.ToInt16(datagridview.Rows[selectedRowIndex].Cells[3].Value); } else { selectedSessionID = Convert.ToInt16(IDSessionLabel.Text); } try { using (ITerminalServer server = new PuzzelLibrary.Terminal.Explorer().GetRemoteServer(HostName)) { server.Open(); ITerminalServicesSession session = server.GetSession(selectedSessionID); if (sender is ToolStripMenuItem) { switch (((ToolStripMenuItem)sender).Name) { case nameof(menuItemSessionDisconnect): { session.Disconnect(); MessageBox.Show(new Form() { TopMost = true }, "Sesja została rozłączona", "Rozłączanie sesji", MessageBoxButtons.OK, MessageBoxIcon.Information); BtnRefresh_Click(sender, e); break; } case nameof(menuItemSessionSendMessage): { using (var terms = new ExplorerFormSendMessage(HostName, selectedSessionID)) { terms.ShowDialog(); MessageBox.Show("Wiadomość wysłano", "Informacja", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; } case nameof(menuItemSessionRemoteControl): { var ADCompResult = PuzzelLibrary.AD.Computer.Search.ByComputerName(HostName, "operatingSystemVersion"); var osVersionComplete = ADCompResult[0].GetDirectoryEntry().Properties["operatingSystemVersion"].Value.ToString().Split(" "); double osVersion = Convert.ToDouble(osVersionComplete[0].Replace('.', ',')); if (osVersion > 6.1) { PuzzelLibrary.ProcessExecutable.ProcExec.StartSimpleProcess("mstsc.exe", "/v:" + HostName + " /shadow:" + selectedSessionID + " /control /NoConsentPrompt"); } else { PuzzelLibrary.Terminal.TerminalExplorer Term = new PuzzelLibrary.Terminal.TerminalExplorer(); Term.ConnectToSession(HostName, selectedSessionID); } break; } case nameof(menuItemSessionLogoff): { session.Logoff(); MessageBox.Show(new Form() { TopMost = true }, "Sesja została wylogowana", "Wylogowywanie sesji", MessageBoxButtons.OK, MessageBoxIcon.Information); BtnRefresh_Click(sender, e); break; } case nameof(menuItemSessionStatus): { DynaStatusTab(session, selectedSessionID); break; } case nameof(menuItemSessionProcesses): { DynaProcessTab(server, session, selectedSessionID); break; } case "KillProcess": { var processId = Convert.ToInt16(datagridview.Rows[selectedRowIndex].Cells[4].Value); var process = server.GetProcess(processId); process.Kill(); RefreshProcesses(sender, server, session, selectedSessionID); MessageBox.Show("Zabito aplikację"); break; } } } else { switch (((Button)sender).Name) { case nameof(btnRefreshNow): { if (tabControl.SelectedTab.Name == "dynaProcesTab") { RefreshProcesses(sender, server, session, selectedSessionID); break; } if (tabControl.SelectedTab.Name == "dynaStatusTab") { RefreshStatus(session, selectedSessionID); break; } break; } } } server.Close(); } } catch (Exception ex) { PuzzelLibrary.Debug.LogsCollector.GetLogs(ex, HostName); } }
private void DynaProcessTab(ITerminalServer server, ITerminalServicesSession session, int selectedSessionID) { TabPage dynaProcessTabPage = new TabPage { Location = new System.Drawing.Point(4, 22), Name = "dynaProcesTab", Size = new System.Drawing.Size(629, 623), Text = "Procesy", UseVisualStyleBackColor = true }; ContextMenuStrip contextProcessMenuStrip = new ContextMenuStrip { Font = new System.Drawing.Font("Tahoma", 8F), ShowImageMargin = false, }; ToolStripMenuItem killprocess = new ToolStripMenuItem { Text = "Zabij proces", Name = "KillProcess" }; killprocess.Click += new EventHandler(ContextMenus); contextProcessMenuStrip.Items.Add(killprocess); DataGridView dynaDataGridView = new DataGridView { AllowUserToAddRows = false, AllowUserToDeleteRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells, AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders, BackgroundColor = System.Drawing.SystemColors.ControlLightLight, ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single, GridColor = System.Drawing.Color.DarkGray, Location = new System.Drawing.Point(0, 0), ReadOnly = true, MultiSelect = false, Name = "DataGridView", RowHeadersVisible = false, SelectionMode = DataGridViewSelectionMode.FullRowSelect, Size = DataGridView.Size, ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleLeft, BackColor = System.Drawing.SystemColors.Control, Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))), ForeColor = System.Drawing.SystemColors.WindowText, SelectionBackColor = System.Drawing.SystemColors.Control, SelectionForeColor = System.Drawing.SystemColors.WindowText, WrapMode = DataGridViewTriState.False, }, ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize, }; dynaDataGridView.Columns.AddRange(new DataGridViewColumn[] { new DataGridViewTextBoxColumn { HeaderText = "Serwer", Width = 64 }, new DataGridViewTextBoxColumn { HeaderText = "Użytkownik", Width = 86 }, new DataGridViewTextBoxColumn { HeaderText = "Sesja", Width = 57 }, new DataGridViewTextBoxColumn { HeaderText = "ID", Width = 42 }, new DataGridViewTextBoxColumn { HeaderText = "Proces ID", Width = 78 }, new DataGridViewTextBoxColumn { HeaderText = "Obraz", Width = 59, AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill } }); foreach (ITerminalServicesProcess process in server.GetProcesses()) { if (process.SessionId == selectedSessionID) { dynaDataGridView.Rows.Add(session.Server.ServerName, session.UserName, session.WindowStationName, process.SessionId, process.ProcessId, process.ProcessName); } } labelSessionCount.Text = "Lista procesów: " + dynaDataGridView.Rows.Count; dynaProcessTabPage.Text += " (" + dynaDataGridView.Rows[0].Cells[1].Value.ToString() + ")"; dynaProcessTabPage.Controls.AddRange (new Control[] { dynaDataGridView }); dynaDataGridView.ContextMenuStrip = contextProcessMenuStrip; tabControl.Controls.Add(dynaProcessTabPage); tabControl.SelectedTab = dynaProcessTabPage; }
private async void InsertToDatabase(ITerminalServicesSession session, SuncatLog log) { try { using (var connection = new SqlConnection("Data Source=server;Database=master;User ID=user;Password=password")) { await connection.OpenAsync(); //if (log.Event == SuncatLogEvent.OpenURL) //{ // connection.ChangeDatabase("ip2location"); // // speed up the query by forcing SQL Server to use the indexes // using (var command = new SqlCommand(@" // SELECT // country_code, // country_name, // region_name, // city_name, // latitude, // longitude, // zip_code, // time_zone // FROM ip2location_db11 // WHERE ip_from = ( // SELECT MAX(ip_from) // FROM ip2Location_db11 // WHERE ip_from <= @Ip // ) // AND ip_to = ( // SELECT MIN(ip_to) // FROM ip2Location_db11 // WHERE ip_to >= @Ip // ) // ", connection)) // { // try // { // var host = new Uri(log.Data1).DnsSafeHost; // var ip = Dns.GetHostAddresses(host).First(); // remoteIp = ip.ToString(); // var bytes = ip.GetAddressBytes(); // var ip2int = (uint)IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(bytes, 0)); // var ipParam = new SqlParameter("@Ip", SqlDbType.BigInt); // ipParam.Value = ip2int; // command.Parameters.Add(ipParam); // using (var dataReader = await command.ExecuteReaderAsync()) // { // if (await dataReader.ReadAsync()) // { // countryCode = dataReader.GetString(0); // countryName = dataReader.GetString(1); // regionName = dataReader.GetString(2); // cityName = dataReader.GetString(3); // latitude = dataReader.GetDouble(4); // longitude = dataReader.GetDouble(5); // zipCode = dataReader.GetString(6); // timeZone = dataReader.GetString(7); // } // } // } // catch (Exception ex) // { // #if DEBUG // Debug.WriteLine(ex); // if (ex.InnerException != null) // Debug.WriteLine(ex.InnerException); // #else // Trace.WriteLine(ex); // if (ex.InnerException != null) // Trace.WriteLine(ex.InnerException); // #endif // } // } //} connection.ChangeDatabase("Suncat"); using (var command = new SqlCommand(@" INSERT INTO SuncatLogs ( DATETIME, EVENT, DATA1, DATA2, DATA3, COMPUTERNAME, USERNAME, LOCALIP, MACADDRESS ) VALUES ( @DateTime, @Event, @Data1, @Data2, @Data3, @ComputerName, @UserName, @LocalIp, @MacAddress ) ", connection)) { var data1 = log.Data1; var data2 = log.Data2; var data3 = log.Data3; var localIp = SystemInformation.GetIPv4Address(); var macAddress = SystemInformation.GetMACAddress(); command.Parameters.AddWithValue("@DateTime", log.DateTime); command.Parameters.AddWithValue("@Event", log.Event.ToString()); command.Parameters.AddWithValue("@Data1", string.IsNullOrWhiteSpace(data1) ? (object)DBNull.Value : data1); command.Parameters.AddWithValue("@Data2", string.IsNullOrWhiteSpace(data2) ? (object)DBNull.Value : data2); command.Parameters.AddWithValue("@Data3", string.IsNullOrWhiteSpace(data3) ? (object)DBNull.Value : data3); command.Parameters.AddWithValue("@ComputerName", Environment.MachineName ?? string.Empty); command.Parameters.AddWithValue("@UserName", session.UserName ?? string.Empty); command.Parameters.AddWithValue("@LocalIp", string.IsNullOrEmpty(localIp) ? (object)DBNull.Value : localIp); command.Parameters.AddWithValue("@MacAddress", string.IsNullOrEmpty(macAddress) ? (object)DBNull.Value : macAddress); await command.ExecuteNonQueryAsync(); } } } catch (Exception ex) { #if DEBUG Debug.WriteLine(ex); if (ex.InnerException != null) { Debug.WriteLine(ex.InnerException); } #else Trace.WriteLine(ex); if (ex.InnerException != null) { Trace.WriteLine(ex.InnerException); } #endif } }
private void DynaStatusTab(ITerminalServicesSession session, int selectedSessionID) { TabPage dynaStatusTabPage = new TabPage { Location = new System.Drawing.Point(4, 22), Name = "dynaStatusTab", Size = new System.Drawing.Size(629, 623), Text = "Status", UseVisualStyleBackColor = true, Padding = new System.Windows.Forms.Padding(3) }; IDSessionLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(151, 3), Size = new System.Drawing.Size(0, 13), }; resolutionValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 365), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; hardwareIDValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 330), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; encryptionLevelValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 295), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; depthValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 260), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; productidValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 225), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; catalogValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 190), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; addressIPValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 155), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; hostNameValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 120), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; nicValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 85), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; userNameValueLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(287, 50), Size = new System.Drawing.Size(66, 13), Text = "brak danych" }; resolutionLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 365), Size = new System.Drawing.Size(75, 13), Text = "Rozdzielczość" }; hardwareIDLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 330), Size = new System.Drawing.Size(51, 31), Text = "Sprzęt ID" }; bytesFramesOutLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(423, 120), Size = new System.Drawing.Size(13, 13), Text = "0" }; framesOutLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(423, 85), Size = new System.Drawing.Size(13, 13), Text = "0" }; bytesOutLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(423, 50), Size = new System.Drawing.Size(13, 13), Text = "0" }; compressionLevelLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(276, 155), Size = new System.Drawing.Size(29, 13), Text = "Brak" }; bytesFramesInLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(276, 120), Size = new System.Drawing.Size(13, 13), Text = "0" }; framesInLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(276, 85), Size = new System.Drawing.Size(13, 13), Text = "0" }; bytesInLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(276, 50), Size = new System.Drawing.Size(13, 13), Text = "0" }; outPacketLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(423, 20), Size = new System.Drawing.Size(70, 13), Text = "Wychodzące" }; inPacketLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(276, 20), Size = new System.Drawing.Size(74, 13), Text = "Przychodzące" }; bytesPerFrameLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(137, 120), Size = new System.Drawing.Size(73, 13), Text = "Bajtów/ramkę" }; compressionLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(120, 155), Size = new System.Drawing.Size(90, 13), Text = "Stopień kompresji" }; framesLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(173, 85), Size = new System.Drawing.Size(37, 13), Text = "Ramki" }; bytesLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(180, 50), Size = new System.Drawing.Size(30, 13), Text = "Bajty" }; encryptionLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 295), Size = new System.Drawing.Size(99, 13), Text = "Poziom szyfrowania" }; depthLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 260), Size = new System.Drawing.Size(79, 13), Text = "Głębia kolorów" }; productIDLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 225), Size = new System.Drawing.Size(58, 13), Text = "Produkt ID" }; catalogLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 190), Size = new System.Drawing.Size(43, 13), Text = "Katalog" }; addressIPLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 155), Size = new System.Drawing.Size(47, 13), Text = "Adres IP" }; hostNameLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 120), Size = new System.Drawing.Size(74, 13), Text = "Nazwa klienta" }; nicLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 85), Size = new System.Drawing.Size(76, 13), Text = "Karta sieciowa" }; userNameLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 50), Size = new System.Drawing.Size(102, 13), Text = "Nazwa użytkownika" }; statusSessionLabel = new Label { AutoSize = true, Location = new System.Drawing.Point(8, 3), Size = new System.Drawing.Size(139, 13), Text = "Status zalogowanej sesji ID" }; GroupBox statusIO = new GroupBox { Location = new System.Drawing.Point(11, 400), Size = new System.Drawing.Size(510, 180), TabStop = false, Text = "Stan wejścia/wyjścia" }; dynaStatusTabPage.Text += " (" + session.UserName + ")"; statusIO.Controls.Add(bytesFramesOutLabel); statusIO.Controls.Add(framesOutLabel); statusIO.Controls.Add(bytesOutLabel); statusIO.Controls.Add(compressionLevelLabel); statusIO.Controls.Add(bytesFramesInLabel); statusIO.Controls.Add(framesInLabel); statusIO.Controls.Add(bytesInLabel); statusIO.Controls.Add(bytesLabel); statusIO.Controls.Add(framesLabel); statusIO.Controls.Add(compressionLabel); statusIO.Controls.Add(bytesPerFrameLabel); statusIO.Controls.Add(inPacketLabel); statusIO.Controls.Add(outPacketLabel); dynaStatusTabPage.Controls.Add(IDSessionLabel); dynaStatusTabPage.Controls.Add(resolutionValueLabel); dynaStatusTabPage.Controls.Add(hardwareIDValueLabel); dynaStatusTabPage.Controls.Add(encryptionLevelValueLabel); dynaStatusTabPage.Controls.Add(depthValueLabel); dynaStatusTabPage.Controls.Add(productidValueLabel); dynaStatusTabPage.Controls.Add(catalogValueLabel); dynaStatusTabPage.Controls.Add(addressIPValueLabel); dynaStatusTabPage.Controls.Add(hostNameValueLabel); dynaStatusTabPage.Controls.Add(nicValueLabel); dynaStatusTabPage.Controls.Add(userNameValueLabel); dynaStatusTabPage.Controls.Add(resolutionLabel); dynaStatusTabPage.Controls.Add(hardwareIDLabel); dynaStatusTabPage.Controls.Add(statusIO); dynaStatusTabPage.Controls.Add(encryptionLabel); dynaStatusTabPage.Controls.Add(depthLabel); dynaStatusTabPage.Controls.Add(productIDLabel); dynaStatusTabPage.Controls.Add(catalogLabel); dynaStatusTabPage.Controls.Add(addressIPLabel); dynaStatusTabPage.Controls.Add(hostNameLabel); dynaStatusTabPage.Controls.Add(nicLabel); dynaStatusTabPage.Controls.Add(userNameLabel); dynaStatusTabPage.Controls.Add(statusSessionLabel); if (session.UserAccount != null) { IDSessionLabel.Text = selectedSessionID.ToString(); userNameValueLabel.Text = session.UserName; hostNameValueLabel.Text = session.ClientName; if (session.ClientIPAddress != null) { addressIPValueLabel.Text = session.ClientIPAddress.ToString(); } else { addressIPValueLabel.Text = "brak danych"; } catalogValueLabel.Text = session.ClientDirectory; productidValueLabel.Text = session.ClientProductId.ToString(); depthValueLabel.Text = session.ClientDisplay.BitsPerPixel.ToString(); hardwareIDValueLabel.Text = session.ClientHardwareId.ToString(); resolutionValueLabel.Text = (session.ClientDisplay.HorizontalResolution + " x " + session.ClientDisplay.VerticalResolution).ToString(); bytesInLabel.Text = session.IncomingStatistics.Bytes.ToString(); framesInLabel.Text = session.IncomingStatistics.Frames.ToString(); if (session.IncomingStatistics.Bytes > 0 && session.IncomingStatistics.Frames > 0) { bytesFramesInLabel.Text = Math.Floor(Convert.ToDecimal(session.IncomingStatistics.Bytes / session.IncomingStatistics.Frames)).ToString(); } else { bytesFramesOutLabel.Text = "brak danych"; } bytesOutLabel.Text = session.OutgoingStatistics.Bytes.ToString(); framesOutLabel.Text = session.OutgoingStatistics.Frames.ToString(); if (session.OutgoingStatistics.Bytes > 0 && session.OutgoingStatistics.Frames > 0) { bytesFramesOutLabel.Text = Math.Floor(Convert.ToDecimal(session.OutgoingStatistics.Bytes / session.OutgoingStatistics.Frames)).ToString(); } else { bytesFramesOutLabel.Text = "brak danych"; } } tabControl.Controls.Add(dynaStatusTabPage); tabControl.SelectedTab = dynaStatusTabPage; }
private void RefreshStatus(ITerminalServicesSession session, int selectedSessionID) { if (session.UserAccount != null) { IDSessionLabel.Text = null; IDSessionLabel.Text = selectedSessionID.ToString(); userNameValueLabel.Text = session.UserName; hostNameValueLabel.Text = session.ClientName; if (session.ClientIPAddress != null) { addressIPValueLabel.Text = session.ClientIPAddress.ToString(); } else { addressIPValueLabel.Text = "brak danych"; } catalogValueLabel.Text = session.ClientDirectory; productidValueLabel.Text = session.ClientProductId.ToString(); depthValueLabel.Text = session.ClientDisplay.BitsPerPixel.ToString(); hardwareIDValueLabel.Text = session.ClientHardwareId.ToString(); resolutionValueLabel.Text = (session.ClientDisplay.HorizontalResolution + " x " + session.ClientDisplay.VerticalResolution).ToString(); bytesInLabel.Text = session.IncomingStatistics.Bytes.ToString(); framesInLabel.Text = session.IncomingStatistics.Frames.ToString(); if (session.IncomingStatistics.Bytes > 0 && session.IncomingStatistics.Frames > 0) { bytesFramesInLabel.Text = Math.Floor(Convert.ToDecimal(session.IncomingStatistics.Bytes / session.IncomingStatistics.Frames)).ToString(); } else { bytesFramesOutLabel.Text = "brak danych"; } bytesOutLabel.Text = session.OutgoingStatistics.Bytes.ToString(); framesOutLabel.Text = session.OutgoingStatistics.Frames.ToString(); if (session.OutgoingStatistics.Bytes > 0 && session.OutgoingStatistics.Frames > 0) { bytesFramesOutLabel.Text = Math.Floor(Convert.ToDecimal(session.OutgoingStatistics.Bytes / session.OutgoingStatistics.Frames)).ToString(); } else { bytesFramesOutLabel.Text = "brak danych"; } } framesOutLabel.Refresh(); bytesFramesOutLabel.Refresh(); bytesOutLabel.Refresh(); bytesFramesInLabel.Refresh(); framesInLabel.Refresh(); bytesInLabel.Refresh(); resolutionValueLabel.Refresh(); hardwareIDValueLabel.Refresh(); depthValueLabel.Refresh(); productidValueLabel.Refresh(); catalogValueLabel.Refresh(); addressIPValueLabel.Refresh(); IDSessionLabel.Refresh(); hostNameValueLabel.Refresh(); hostNameValueLabel.Refresh(); }
public string FormatedSession(ITerminalServicesSession session) { System.Text.StringBuilder data = new System.Text.StringBuilder(); data.Append(session.UserName); for (int i = 0; i < "Nazwa użytkownika ".Length - session.UserName.Length; i++) { data.Append(" "); } data.Append(session.WindowStationName); for (int i = 0; i < "Nazwa Sesji ".Length - session.WindowStationName.Length; i++) { data.Append(" "); } string IPAddress; if (session.ConnectionState != ConnectionState.Disconnected && session.ClientProtocolType != ClientProtocolType.Console) { IPAddress = (session.ClientIPAddress.ToString()); } else { IPAddress = "Niedostępne"; } data.Append(IPAddress); for (int i = 0; i < " IP klienta ".Length - IPAddress.Length; i++) { data.Append(" "); } data.Append(session.SessionId); for (int i = 0; i < " Id ".Length - session.SessionId.ToString().Length; i++) { data.Append(" "); } data.Append(session.ConnectionState); for (int i = 0; i < "Status ".Length - session.ConnectionState.ToString().Length; i++) { data.Append(" "); } //Wyekstraktowanie całego czasu bezczynności int time = Convert.ToInt32(Math.Ceiling(((TimeSpan)session.IdleTime).TotalSeconds)); double _time = 0; string idletime = ""; if ((time / 3600) >= 1) { _time = (time / 3600); idletime += (Math.Ceiling(_time).ToString() + ":"); time -= Convert.ToInt32(Math.Ceiling(_time)) * 3600; } if ((time / 60) > 1) { _time = (time / 60); idletime += (Math.Ceiling(_time).ToString() + ":"); time -= Convert.ToInt32(Math.Ceiling(_time)) * 60; } idletime += (time.ToString()); data.Append(idletime); for (int i = 0; i < "Czas bezczynności ".Length - idletime.Length; i++) { data.Append(" "); } data.Append(session.LoginTime); data.Append("\n"); return(data.ToString()); }