private static int RunListServicesAndReturnExitCode(ListOptions opts) { //Check Admin right if (!DaemonMasterUtils.IsElevated()) { Console.WriteLine("You must start the program with admin rights."); return(1); } try { Console.WriteLine("Number: service name / display name"); List <DmServiceDefinition> services = RegistryManagement.GetInstalledServices(); for (var i = 0; i < services.Count; i++) { var sb = new StringBuilder(); sb.Append(i); sb.Append(": "); sb.Append(services[i].ServiceName.Contains("DaemonMaster_") ? services[i].ServiceName.Remove(0, 13) : services[i].ServiceName); //Remove internally used prefix TODO: remove that on a later release sb.Append(" / "); sb.Append(services[i].DisplayName); Console.WriteLine(sb); } return(0); } catch (Exception ex) { Console.WriteLine(ex.Message); return(1); } }
private void AskToEnableInteractiveServices() { try { //Ask the user if the key is no set if (RegistryManagement.CheckInteractiveServices()) { return; } MessageBoxResult result = MessageBox.Show(_resManager.GetString("interactive_service_regkey_not_set"), _resManager.GetString("question"), MessageBoxButton.YesNo, MessageBoxImage.Question); if (result != MessageBoxResult.Yes) { return; } if (RegistryManagement.EnableInteractiveServices(true)) { return; } MessageBox.Show(_resManager.GetString("problem_occurred"), _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(_resManager.GetString("failed_to_set_interServ") + "\n" + ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
private void OpenServiceItemMessageExecute(OpenEditServiceWindowMessage obj) { //// If it's not the view model of this view => return if (!_viewModel.Equals(obj.Sender)) { return; } //Check if already one window with the same service is opened (from this instance) => when true show and focus it //var editServiceWindows = Application.Current.Windows.OfType<ServiceEditWindow>(); var editServiceWindows = OwnedWindows.OfType <ServiceEditWindow>(); var addWindow = editServiceWindows.FirstOrDefault(x => x.WindowIdentifier == (obj.ServiceItem?.ServiceName ?? string.Empty)); if (addWindow != default) { addWindow.Show(); addWindow.Focus(); return; } DmServiceDefinition data = obj.ServiceItem != null?RegistryManagement.LoadFromRegistry(obj.ServiceItem.ServiceName) : null; //TODO: MVVM also use show later... var window = new ServiceEditWindow(data) { Owner = this, DataContext = new NewEditViewModel(), ReadOnlyMode = obj.ReadOnlyMode, OriginalItem = obj.ServiceItem, WindowIdentifier = obj.ServiceItem?.ServiceName ?? string.Empty, WindowStartupLocation = WindowStartupLocation.CenterOwner }; window.Show(); }
/// <summary> /// Load predefined settings. /// </summary> private void SettingsLoad() { // Creating the history file directory in USERPROFILE\AppData\Local if not exist. if (!Directory.Exists(s_historyFilePath)) { Directory.CreateDirectory(s_historyFilePath); } //creating history file if not exist if (!File.Exists(s_historyFile)) { File.WriteAllText(s_historyFile, Environment.NewLine); } // Creating the Password Manager directory for storing the encrypted files. if (!Directory.Exists(s_passwordManagerDirectory)) { Directory.CreateDirectory(s_passwordManagerDirectory); } //Store current directory with current process id. StoreCurrentDirectory(); // Creating the addon directory for C# code script scomands if not exist. if (!Directory.Exists(s_addonDir)) { Directory.CreateDirectory(s_addonDir); } //reading current location s_currentDirectory = File.ReadAllText(GlobalVariables.currentDirectory); if (s_currentDirectory == "") { File.WriteAllText(GlobalVariables.currentDirectory, GlobalVariables.rootPath); } // Reading cport time out setting and set default vaule if is emtpy. string timeOut = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut); if (timeOut == "") { RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut, "500"); } // Reading UI settings. s_regUI = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regUI); if (s_regUI == "") { RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regUI, @"green;1|white;$|cyan"); } // Title display application name, version + current directory. Console.Title = $"{s_terminalTitle} | {s_currentDirectory}"; // Store xTerminal version. GlobalVariables.version = Application.ProductVersion; }
public void Execute(string arg) { if (arg.Length == 2) { Console.WriteLine($"Use -h param for {Name} command usage!"); return; } _regUI = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regUI); var args = arg.Split(' '); // Sore userinfo settings. if (arg.ContainsText("-u")) { if (arg.ContainsText(":e")) { SetUserColor(args.ParameterAfter("-c"), _regUI, "", true, Core.SystemTools.UI.Setting.UserInfo); return; } else if (arg.ContainsText(":d")) { SetUserColor(args.ParameterAfter("-c"), _regUI, "", false, Core.SystemTools.UI.Setting.UserInfo); return; } } // Store indicator setting. if (arg.ContainsText("-i")) { if (arg.ContainsText("-s")) { SetUserColor(args.ParameterAfter("-c"), _regUI, args.ParameterAfter("-s"), true, Core.SystemTools.UI.Setting.Indicator); return; } SetUserColor(args.ParameterAfter("-c"), _regUI, "$", true, Core.SystemTools.UI.Setting.Indicator); return; } // Store current directory setting. if (arg.ContainsText("-cd")) { SetUserColor(args.ParameterAfter("-cd"), _regUI, "$", true, Core.SystemTools.UI.Setting.CurrentDirectoy); return; } // Display help message if (arg == $"{Name} -h") { Console.WriteLine(_helpMessage); } }
private void MenuItem_RefreshListOnClick(object sender, RoutedEventArgs e) { //Clear the list and refill it so that the event gets fired _processCollection.Clear(); List <ServiceListViewItem> list = RegistryManagement.LoadInstalledServices().ConvertAll(x => new ServiceListViewItem(x.ServiceName, x.DisplayName, x.BinaryPath, Equals(x.Credentials, ServiceCredentials.LocalSystem))); foreach (ServiceListViewItem item in list) { _processCollection.Add(item); } //Force Update after refresh UpdateListView(null, EventArgs.Empty); }
protected override void OnStart(string[] args) { base.OnStart(args); try { //Get the service name _serviceName = GetServiceName(); //Get data from registry _serviceDefinition = RegistryManagement.LoadServiceStartInfosFromRegistry(_serviceName); //-------------------------------------------------------------------- //Setup NLOG for the service if (_serviceDefinition.UseEventLog) { SetupEventLogService(); } //Request additional time RequestAdditionalTime(_serviceDefinition.ProcessTimeoutTime + 1000); //Create a new DmProcess instance with reg data _dmProcess = new DmProcess(_serviceDefinition); _dmProcess.MaxRestartsReached += DmProcessOnMaxRestartsReached; _dmProcess.UpdateProcessPid += DmProcessOnUpdateProcessPid; //Check if the service should start in a user session or in the service session string sessionUsername = RegistryManagement.ReadAndClearSessionUsername(_serviceName); if (string.IsNullOrWhiteSpace(sessionUsername)) { Logger.Info("Starting the process in service session..."); _dmProcess.StartProcess(null); } else { Logger.Info("Starting the process in user session..."); _dmProcess.StartProcess(sessionUsername); } } catch (Exception ex) { Logger.Error(ex, ex.Message); Stop(); } }
private static int RunInstallAndReturnExitCode(InstallOptions opts) { //Check Admin right if (!DaemonMasterUtils.IsElevated()) { Console.WriteLine("You must start the program with admin rights."); return(1); } //------------------------ if (string.IsNullOrWhiteSpace(opts.ServiceName)) { Console.WriteLine("The given service name is invalid."); return(-1); } var serviceDefinition = new DmServiceDefinition(opts.ServiceName) { BinaryPath = opts.FullPath, DisplayName = opts.DisplayName }; try { CheckAndSetCommonArguments(ref serviceDefinition, opts); //Install service using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.CreateService)) { scm.CreateService(serviceDefinition); } //Save arguments in registry RegistryManagement.SaveInRegistry(serviceDefinition); Console.WriteLine("Successful!"); return(0); } catch (Exception ex) { Console.WriteLine(ex.Message); return(1); } }
/// <inheritdoc /> public ServiceListViewItem Show(ServiceListViewItem item, EditWindowServiceCommand command = EditWindowServiceCommand.EditOrCreate) { //TODO: MVVM var dialog = new ServiceEditWindow(item != null ? RegistryManagement.LoadFromRegistry(item.ServiceName) : null) { OriginalItem = item, ReadOnlyMode = command == EditWindowServiceCommand.ViewOnly }; dialog.Show(); //var result = dialog.ShowDialog(); //if (result.HasValue && result.Value) //{ // return new ServiceListViewItem(dialog.GetServiceStartInfo()); //} return(null); }
public void Execute(string arg) { string file = string.Empty; string set; string dlocation = File.ReadAllText(GlobalVariables.currentDirectory); string cEditor = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regCurrentEitor); if (cEditor == "") { RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regCurrentEitor, "notepad"); } try { if (!arg.Contains("set")) { int argLenght = arg.Length - 5; file = arg.Substring(5, argLenght); file = FileSystem.SanitizePath(file, dlocation); ProcessCall(file, File.Exists(cEditor) ? cEditor : "notepad"); return; } set = arg.Replace("edit set ", ""); if (File.Exists(set)) { RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regCurrentEitor, set); Console.WriteLine("Your New editor is: " + set); return; } FileSystem.ErrorWriteLine($"File {set} dose not exist"); return; } catch { file = FileSystem.SanitizePath(file, dlocation); if (string.IsNullOrEmpty(file)) { Console.WriteLine("You must type the file name for edit!"); return; } ProcessCall(file, File.Exists(cEditor) ? cEditor : "notepad"); return; } }
public MainWindow() { //Initialize GUI InitializeComponent(); //Get the configuration _config = ConfigManagement.GetConfig; //Fill the list and subs to the event _processCollection = new ObservableCollection <ServiceListViewItem>(RegistryManagement.LoadInstalledServices().ConvertAll(x => new ServiceListViewItem(x.ServiceName, x.DisplayName, x.BinaryPath, Equals(x.Credentials, ServiceCredentials.LocalSystem)))); _processCollection.CollectionChanged += ProcessCollectionOnCollectionChanged; //Start ListView updater StartListViewUpdateTimer(_config.UpdateInterval); //Show the list in the list view ListViewDaemons.ItemsSource = _processCollection; }
private void SetUserColor(string color, string settings, string indicator, bool enable, Core.SystemTools.UI.Setting setting) { try { int indexColor = _colors.FindIndex(c => c == color.ToLower()); string outColor = _colors[indexColor]; string colorSetting; if (setting.ToString() == "Indicator") { int indexIndicator = _indicators.FindIndex(i => i == indicator); string indiOut = _indicators[indexIndicator]; colorSetting = $"{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.UserInfo)}|{outColor};{indiOut}|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.CurrentDirectoy)}"; RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regUI, colorSetting); } else if (setting.ToString() == "UserInfo") { if (enable) { colorSetting = $"{outColor};1|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.Indicator)}|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.CurrentDirectoy)}"; RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regUI, colorSetting); return; } colorSetting = $"{outColor};0|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.Indicator)}|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.CurrentDirectoy)}"; RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regUI, colorSetting); } else if (setting.ToString() == "CurrentDirectoy") { colorSetting = $"{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.UserInfo)}|{Core.SystemTools.UI.SanitizeSettings(settings, Core.SystemTools.UI.Setting.Indicator)}|{outColor}"; RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regUI, colorSetting); } } catch (ArgumentOutOfRangeException) { FileSystem.ErrorWriteLine($"Color or indicator is not supported. Check command please!"); } catch (Exception e) { FileSystem.ErrorWriteLine(e.ToString()); } }
private void StartService(ServiceListViewItem serviceListViewItem, bool inUserSession = false) { try { if (inUserSession) { //Write username where the service should start the process RegistryManagement.WriteSessionUsername(serviceListViewItem.ServiceName, WindowsIdentity.GetCurrent().Name); } using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect)) { using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.Start)) { serviceHandle.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
// Grap processor information from registry. private void GetProcesorInfo(string cpuInfoWMI, string coresInfo) { string procInfo = RegistryManagement.regKey_ReadMachine(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString"); FileSystem.ColorConsoleText(ConsoleColor.Green, "CPU"); Console.WriteLine($": {procInfo}"); using (var sRead = new StringReader(cpuInfoWMI)) { string lineCPUCount; while ((lineCPUCount = sRead.ReadLine()) != null) { if (lineCPUCount.StartsWith("NumberOfProcessors")) { string outParam = ""; outParam += lineCPUCount.Split(':')[1]; FileSystem.ColorConsoleText(ConsoleColor.Green, $"Physical CPU's"); Console.WriteLine($": {outParam}"); } } } using (var sRead = new StringReader(coresInfo)) { string lineCoresCount; while ((lineCoresCount = sRead.ReadLine()) != null) { if (lineCoresCount.StartsWith("NumberOfCores")) { string outParam = ""; outParam += lineCoresCount.Split(':')[1]; FileSystem.ColorConsoleText(ConsoleColor.Green, $"CPU(s) Cores"); Console.WriteLine($": {outParam}"); } } } FileSystem.ColorConsoleText(ConsoleColor.Green, $"Logical CPU's"); Console.WriteLine($": {Environment.ProcessorCount}"); }
private void LoadServiceInfos() { #region GeneralTab //Set to readonly when it has already a service name if (!string.IsNullOrWhiteSpace(_tempServiceConfig.ServiceName)) { TextBoxServiceName.Text = _tempServiceConfig.ServiceName; } if (!_createNewService) { TextBoxServiceName.IsReadOnly = true; TextBoxServiceName.Foreground = Brushes.Gray; TextBoxServiceName.BorderBrush = Brushes.LightGray; } TextBoxDisplayName.Text = _tempServiceConfig.DisplayName; if (!string.IsNullOrWhiteSpace(_tempServiceConfig.BinaryPath)) { TextBoxFilePath.Text = _tempServiceConfig.BinaryPath; } TextBoxParam.Text = _tempServiceConfig.Arguments; TextBoxDescription.Text = _tempServiceConfig.Description; //StartType switch (_tempServiceConfig.StartType) { case Advapi32.ServiceStartType.AutoStart: ComboBoxStartType.SelectedIndex = _tempServiceConfig.DelayedStart ? 1 : 0; break; case Advapi32.ServiceStartType.StartOnDemand: ComboBoxStartType.SelectedIndex = 2; break; case Advapi32.ServiceStartType.Disabled: ComboBoxStartType.SelectedIndex = 3; break; default: ComboBoxStartType.SelectedIndex = 0; break; } #endregion #region CustomUser if (Equals(_tempServiceConfig.Credentials, ServiceCredentials.LocalSystem)) { TextBoxUsername.Clear(); TextBoxPassword.Clear(); CheckBoxUseLocalSystem.IsChecked = true; CheckBoxUseVirtualAccount.IsChecked = false; } else if (ServiceCredentials.IsVirtualAccount(_tempServiceConfig.Credentials)) { CheckBoxUseVirtualAccount.IsChecked = true; CheckBoxUseLocalSystem.IsChecked = false; } else { TextBoxUsername.Text = _tempServiceConfig.Credentials.Username; TextBoxPassword.Password = _createNewService ? string.Empty : PLACEHOLDER_PASSWORD; CheckBoxUseLocalSystem.IsChecked = false; CheckBoxUseVirtualAccount.IsChecked = false; } #endregion #region AdvancedTab TextBoxMaxRestarts.Text = _tempServiceConfig.ProcessMaxRestarts.ToString(); TextBoxProcessTimeoutTime.Text = _tempServiceConfig.ProcessTimeoutTime.ToString(); TextBoxProcessRestartDelay.Text = _tempServiceConfig.ProcessRestartDelay.ToString(); TextBoxCounterResetTime.Text = _tempServiceConfig.CounterResetTime.ToString(); TextBoxLoadOrderGroup.Text = _tempServiceConfig.LoadOrderGroup; //Process Priority switch (_tempServiceConfig.ProcessPriority) { case ProcessPriorityClass.Idle: ComboBoxProcessPriority.SelectedIndex = 0; break; case ProcessPriorityClass.BelowNormal: ComboBoxProcessPriority.SelectedIndex = 1; break; case ProcessPriorityClass.Normal: ComboBoxProcessPriority.SelectedIndex = 2; break; case ProcessPriorityClass.AboveNormal: ComboBoxProcessPriority.SelectedIndex = 3; break; case ProcessPriorityClass.High: ComboBoxProcessPriority.SelectedIndex = 4; break; case ProcessPriorityClass.RealTime: ComboBoxProcessPriority.SelectedIndex = 5; break; default: ComboBoxProcessPriority.SelectedIndex = 2; break; } CheckBoxIsConsoleApp.IsChecked = _tempServiceConfig.IsConsoleApplication; RadioButtonUseCtrlC.IsChecked = _tempServiceConfig.UseCtrlC; RadioButtonUseCtrlBreak.IsChecked = !_tempServiceConfig.UseCtrlC; //Hide check box interact with desktop on not supported systems (windows 10 1803+) if (!DaemonMasterUtils.IsSupportedWindows10VersionForIwd) { CheckBoxInteractDesk.IsChecked = false; CheckBoxInteractDesk.IsEnabled = false; } else { CheckBoxInteractDesk.IsChecked = _tempServiceConfig.CanInteractWithDesktop; } CheckBoxUseEventLog.IsChecked = _tempServiceConfig.UseEventLog; #endregion #region Dependency Listboxes #region DependOnService //Load Data into _dependOnServiceObservableCollection _dependOnServiceObservableCollection = new ObservableCollection <ServiceInfo>(); foreach (string dep in _tempServiceConfig.DependOnService) { var serviceInfo = new ServiceInfo { ServiceName = dep }; //Get display name using (var serviceController = new ServiceController(dep)) { serviceInfo.DisplayName = serviceController.DisplayName; } _dependOnServiceObservableCollection.Add(serviceInfo); } //Sort the list in alphabetical order ICollectionView collectionView1 = CollectionViewSource.GetDefaultView(_dependOnServiceObservableCollection); collectionView1.SortDescriptions.Add(new SortDescription("DisplayName", ListSortDirection.Ascending)); ListBoxDependOnService.ItemsSource = collectionView1; #endregion #region AllServices //Load Data into _allServicesObservableCollection _allServicesObservableCollection = new ObservableCollection <ServiceInfo>(); foreach (ServiceController service in ServiceController.GetServices()) { var serviceInfo = new ServiceInfo { DisplayName = service.DisplayName, ServiceName = service.ServiceName }; if (_dependOnServiceObservableCollection.All(x => x.ServiceName != serviceInfo.ServiceName)) { _allServicesObservableCollection.Add(serviceInfo); } } //Sort the list in alphabetical order ICollectionView collectionView2 = CollectionViewSource.GetDefaultView(_allServicesObservableCollection); collectionView2.SortDescriptions.Add(new SortDescription("DisplayName", ListSortDirection.Ascending)); ListBoxAllServices.ItemsSource = collectionView2; #endregion #region AllGroups //Load Data into _allGroupsObservableCollection _allGroupsObservableCollection = new ObservableCollection <string>(RegistryManagement.GetAllServiceGroups()); //Sort the list in alphabetical order ICollectionView collectionView3 = CollectionViewSource.GetDefaultView(_allGroupsObservableCollection); collectionView3.SortDescriptions.Add(new SortDescription()); ListBoxAllGroups.ItemsSource = collectionView3; #endregion #region DependOnGroup //Load Data into _dependOnGroupObservableCollection _dependOnGroupObservableCollection = new ObservableCollection <string>(_tempServiceConfig.DependOnGroup); //Sort the list in alphabetical order ICollectionView collectionView4 = CollectionViewSource.GetDefaultView(_dependOnGroupObservableCollection); collectionView3.SortDescriptions.Add(new SortDescription()); ListBoxDependOnGroup.ItemsSource = collectionView4; #endregion #endregion }
private void EditDaemon() { if (ListViewDaemons.SelectedItem == null) { return; } var serviceListViewItem = (ServiceListViewItem)ListViewDaemons.SelectedItem; //Stop service first using (var serviceController = new ServiceController(serviceListViewItem.ServiceName)) { if (serviceController.Status != ServiceControllerStatus.Stopped) { MessageBoxResult result = MessageBox.Show(_resManager.GetString("you_must_stop_the_service_first"), _resManager.GetString("information"), MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { StopService(serviceListViewItem); try { serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } catch (TimeoutException ex) { //TODO: Better message MessageBox.Show("Cannot stop the service:\n" + ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); return; } } else { return; } } } try { //Open service edit window with the data from registry var serviceEditWindow = new ServiceEditWindow(RegistryManagement.LoadServiceStartInfosFromRegistry(serviceListViewItem.ServiceName)); //stops until windows has been closed bool?dialogResult = serviceEditWindow.ShowDialog(); //Check result if (dialogResult.HasValue && dialogResult.Value) { DmServiceDefinition serviceDefinition = serviceEditWindow.GetServiceStartInfo(); if (string.Equals(serviceDefinition.ServiceName, serviceListViewItem.ServiceName)) { //Update serviceListViewItem _processCollection[_processCollection.IndexOf(serviceListViewItem)] = ServiceListViewItem.CreateFromServiceDefinition(serviceDefinition); } else { //Create new daemon (Import as happend with a diffrent service name => create new service with that name) _processCollection.Add(ServiceListViewItem.CreateFromServiceDefinition(serviceDefinition)); } } } catch (Exception ex) { MessageBox.Show(_resManager.GetString("cannot_load_data_from_registry") + "\n" + ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
public void Execute(string args) { try { GlobalVariables.eventCancelKey = false; string cTimeOut = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut); if (FileSystem.IsNumberAllowed(cTimeOut) && !string.IsNullOrEmpty(cTimeOut)) { s_timeOut = Int32.Parse(cTimeOut); } else { s_timeOut = 500; RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut, "500"); } if (args.StartsWith($"{Name} stimeout")) { string timeOut = args.SplitByText("stimeout ", 1); RegistryManagement.regKey_WriteSubkey(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut, timeOut); Console.Write("New check port time out is: "); FileSystem.ColorConsoleTextLine(ConsoleColor.Green, timeOut + " ms"); return; } if (args == $"{Name} rtimeout") { string timeOut = RegistryManagement.regKey_Read(GlobalVariables.regKeyName, GlobalVariables.regCportTimeOut); Console.Write("Check port time out is set to: "); FileSystem.ColorConsoleTextLine(ConsoleColor.Green, timeOut + " ms"); return; } if (args.Length == 5) { Console.WriteLine($"Use -h param for {Name} command usage!"); return; } if (args == $"{Name} -h") { Console.WriteLine(s_helpMessage); return; } string arg = args.Substring(6, args.Length - 6); string ipAddress = arg.SplitByText(" -p ", 0); if (!NetWork.PingHost(ipAddress)) { FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, $"{ipAddress} is offline"); return; } string portData = arg.SplitByText(" -p ", 1); if (portData.Contains("-")) { GlobalVariables.eventKeyFlagX = true; string[] portsRange = portData.Split('-'); int minPort = Int32.Parse(portsRange[0].Trim()); int maxPort = Int32.Parse(portsRange[1].Trim()); PortScan.RunPortScan(ipAddress, minPort, maxPort, s_timeOut); if (GlobalVariables.eventCancelKey) { FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "Command stopped!"); } GlobalVariables.eventCancelKey = false; return; } int port = Int32.Parse(portData.Trim()); PortScan.RunPortScan(ipAddress, port, port, s_timeOut); if (GlobalVariables.eventCancelKey) { FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "Command stopped!"); } GlobalVariables.eventCancelKey = false; } catch (Exception e) { FileSystem.ErrorWriteLine(e.Message); } }
private static int RunEditReturnExitCode(EditOptions opts) { //Check Admin right if (!DaemonMasterUtils.IsElevated()) { Console.WriteLine("You must start the program with admin rights."); return(1); } //------------------------ DmServiceDefinition serviceDefinition; try { if (string.IsNullOrWhiteSpace(opts.ServiceName)) { Console.WriteLine("The given service name is invalid."); return(-1); } string realServiceName = opts.ServiceName; if (!RegistryManagement.IsDaemonMasterService(realServiceName)) { realServiceName = "DaemonMaster_" + realServiceName; //Check for the name of the old system TODO: remove later if (!RegistryManagement.IsDaemonMasterService(realServiceName)) { Console.WriteLine("Cannot found a DaemonMaster service with the given name."); return(-1); } } //Load data from registry serviceDefinition = RegistryManagement.LoadFromRegistry(realServiceName); } catch (Exception) { Console.WriteLine("Cannot found a service with the given service name."); //"\n" + e.Message + "\n StackTrace: " + e.StackTrace); return(1); } try { CheckAndSetCommonArguments(ref serviceDefinition, opts); //Edit service using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect)) { using (ServiceHandle service = scm.OpenService(serviceDefinition.ServiceName, Advapi32.ServiceAccessRights.AllAccess)) { if (service.QueryServiceStatus().currentState != Advapi32.ServiceCurrentState.Stopped) { Console.WriteLine("Service is not stopped, please stop it first."); return(1); } service.ChangeConfig(serviceDefinition); } } //Save arguments in registry RegistryManagement.SaveInRegistry(serviceDefinition); Console.WriteLine("Successful!"); return(0); } catch (Exception ex) { Console.WriteLine(ex.Message); return(1); } }
private void ApplyConfiguration() { try { //Only set right it is not a build in account if (!Equals(_tempServiceConfig.Credentials, ServiceCredentials.LocalSystem) && !Equals(_tempServiceConfig.Credentials, ServiceCredentials.LocalService) && !Equals(_tempServiceConfig.Credentials, ServiceCredentials.NetworkService) && !Equals(_tempServiceConfig.Credentials, ServiceCredentials.NoChange) && !ServiceCredentials.IsVirtualAccount(_tempServiceConfig.Credentials)) //Normally all NT SERVICE\\... service has that right, so no need to add it. { string username = _tempServiceConfig.Credentials.Username; if (string.IsNullOrWhiteSpace(username)) { username = TextBoxUsername.Text; } using (LsaPolicyHandle lsaWrapper = LsaPolicyHandle.OpenPolicyHandle()) { bool hasRightToStartAsService = lsaWrapper.EnumeratePrivileges(username).Any(x => x.Buffer == "SeServiceLogonRight"); if (!hasRightToStartAsService) { MessageBoxResult result = MessageBox.Show(_resManager.GetString("logon_as_a_service", CultureInfo.CurrentUICulture), _resManager.GetString("question", CultureInfo.CurrentUICulture), MessageBoxButton.YesNo, MessageBoxImage.Question); if (result != MessageBoxResult.Yes) { return; } //Give the account the right to start as service lsaWrapper.AddPrivileges(username, "SeServiceLogonRight"); } } } if (_createNewService) { using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.CreateService)) { scm.CreateService(_tempServiceConfig); ////When no exception has been throwed show up a message (no longer) //MessageBox.Show( // _resManager.GetString("the_service_installation_was_successful", CultureInfo.CurrentUICulture), // _resManager.GetString("success", CultureInfo.CurrentUICulture), MessageBoxButton.OK, MessageBoxImage.Information); } } else { using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect)) { using (ServiceHandle serviceHandle = scm.OpenService(_tempServiceConfig.ServiceName, Advapi32.ServiceAccessRights.AllAccess)) { serviceHandle.ChangeConfig(_tempServiceConfig); } } } //Save settings in registry after no error is occured RegistryManagement.SaveInRegistry(_tempServiceConfig); DialogResult = true; Close(); } catch (Exception ex) { MessageBox.Show( _resManager.GetString("the_service_installation_was_unsuccessful", CultureInfo.CurrentUICulture) + "\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
//Entry point of shell public void Run(string[] args) { // Start keyhook event on background for CTRL+X . s_backgroundWorker = new BackgroundWorker(); s_backgroundWorker.DoWork += KeyHook; s_backgroundWorker.RunWorkerAsync(); // Check if current path subkey exists in registry. RegistryManagement.CheckRegKeysStart(s_listReg, GlobalVariables.regKeyName, "", false); // Setting up the title. s_terminalTitle = s_terminalTitle.Substring(0, s_terminalTitle.Length - 2); Console.Title = s_terminalTitle; if (ExecuteParamCommands(args)) { return; } ; // We loop until exit commands is hit do { //Load predifined settings. SettingsLoad(); // We se the color and user loged in on console. SetConsoleUserConnected(s_currentDirectory, s_accountName, s_computerName, s_regUI); //reading user imput s_input = Console.ReadLine(); //cleaning input s_input = s_input.Trim(); if (File.Exists(s_historyFile)) { WriteHistoryCommandFile(s_historyFile, s_input); //rebooting the machine command if (s_input == "reboot") { SystemCmd.RebootCmd(); } //shuting down the machine command else if (s_input == "shutdown") { SystemCmd.ShutDownCmd(); } //log off the machine command else if (s_input == "logoff") { SystemCmd.LogoffCmd(); } else if (s_input == "lock") { SystemCmd.LockCmd(); } else if (s_input.StartsWith("cmd")) { Execute(s_input, s_input); } else if (s_input.StartsWith("ps")) { Execute(s_input, s_input); } } // New command implementation by Scott. if (GlobalVariables.autoSuggestion) { GlobalVariables.autoSuggestion = false; } else { ExecuteCommands(s_input); } GC.Collect(); } while (s_input != "exit"); }