- How to Allow Non-Admin Users to Start/Stop Windows Service?
- Setting Windows Service Permissions Using the SC.exe (Service controller) Tool
- Using the SubInACL to Allow a User to Start/Stop/Restart Service
- How to Change Windows Service Permission Using Process Explorer?
- Setting Windows Service Permissions Using PowerShell
- Using Security Templates to Manage Service Permissions
- How to Grant Users Rights to Manage a Service using GPO?
- Start or stop Windows service from command line (CMD)
- Практическое руководство. Запуск служб How to: Start Services
- Настройка способа запуска службы To specify how a service should start
- Запуск службы вручную из обозревателя сервера To manually start a service from Server Explorer
- Запуск службы вручную из диспетчера служб To manually start a service from Services Control Manager
- Запуск службы вручную из кода To manually start a service from code
How to Allow Non-Admin Users to Start/Stop Windows Service?
By default, common (non-admin) users cannot manage Windows services. This means that users cannot stop, start, restart, or change the settings/permissions of Windows services. In some cases, it is necessary for a user to have the permissions to restart or manage certain services. In this article we’ll look at several ways to manage the permissions for Windows services. In particular, we’ll show you how to allow a non-admin user to start, stop and restart a specific Windows service by granting the appropriate permissions.
Suppose, you need to grant the domain account contoso\tuser the permissions to restart the Print Spooler service (service name – spooler). When the non-admin tries to restart the service, an error appears:
There is no simple and convenient built-in tool to manage services permissions in Windows. We’ll consider some ways to grant the permissions to a user to manage service:
Setting Windows Service Permissions Using the SC.exe (Service controller) Tool
A standard built-in Windows method to manage system service permissions supposes using the sc.exe (Service Controller) tool. The main problem with using this utility is the complex syntax of the service permissions format (the SDDL format — Security Description Definition Language).
You can get the current permissions for a Windows service as an SDDL string like this:
sc.exe sdshow Spooler
What do all these symbols mean?
The first letter after brackets means: allow (A) or deny (D).
The next set of symbols is assignable permissions.
The last 2 characters are the objects (user, group or SID) that are granted permissions. There is a list of predefined groups.
Instead of a predefined group, you can explicitly specify a user or group by SID. To get the SID for the current user, you can use the command:
Or you can find the SID for any domain user using the Get-ADUser cmdlet:
Get-ADUser -Identity ‘sadams’ | select SID
You can get the SID of the AD security group using the Get-ADGroup cmdlet:
In order to assign the SDDL permissions string for a specific service, you can use the sc sdset command. For example, the permissions can be granted to a user with the following command:
sc sdset Spooler «D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2133228432-2794320136-1823075350-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)»
Using the SubInACL to Allow a User to Start/Stop/Restart Service
It is easier to use a command line tool SubInACL from the Sysinternals (by Mark Russinovich) to manage the service permissions. The syntax of this tool is much easier and more convenient. Here is how you can grant the restart permissions for a service using the SubInACL:
- Download subinacl.msi from this webpage (https://www.microsoft.com/en-us/download/details.aspx?id=23510) and install it on the target system;
- In the elevated command prompt, go to the directory containing the tool: cd “C:\Program Files (x86)\Windows Resource Kits\Tools\»
- Run the command: subinacl.exe /service Spooler /grant=contoso\tuser=PTO
If you did everything right, the service should restart.
subinacl.exe /service Spooler /revoke=contoso\tuser
How to Change Windows Service Permission Using Process Explorer?
You can change Windows service permissions using one more Sysinternals utility – Process Explorer. Run the Process Explorer as administrator and find the process of the service you need. In our example, this is spoolsv.exe (the spooler executable – C:\Windows\System32\spoolsv.exe ). Open the process properties and click the Services tab.
Click the Permissions button and add the user or group in the window that opens. After that select the permissions that you want to assign (Full Control/Write/Read).
Setting Windows Service Permissions Using PowerShell
In TechNet gallery there is a separate unofficial PowerShell module for managing permissions for different Windows objects – PowerShellAccessControl Module (you can download it here). This module also allows you to manage the service permissions. Install this module and import it into your PS session:
You can get the effective permissions for a specific Windows service from PowerShell like this:
Get-Service spooler | Get-EffectiveAccess -Principal corp\tuser
To allow non-admin user to start and stop spooler service, run the command:
Get-Service spooler | Add-AccessControlEntry -ServiceAccessRights Start,Stop -Principal corp\tuser
Using Security Templates to Manage Service Permissions
A visual (but requiring more actions) graphical way to manage service permissions is using Security Templates. Open mmc.exe console and add the Security Templates snap-in.
Create a new security template (New Template).
Specify the name for the new template and go to the System Services section. In the list of services select the service Print Spooler and open its properties.
Select the startup mode (Automatic) and click Edit Security.
Using the Add button, add a user account or a group to grant permissions to. In our case, Start, stop and pause permission is enough.
Save this template.
If you open this file, you can see that the information about the permissions is saved in the SDDL format, mentioned earlier. The string obtained in this way can be used as an argument of the sc.exe command.
[Unicode]
Unicode=yes
[Version]
signature=»$CHICAGO$»
Revision=1
[Service General Setting]
«Spooler»,2,»D:AR(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;RPWPDTRC;;;S-1-5-21-3243688314-1354026805-3292651841-1127)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)»
Now you only have to create a new database (Open Database) using the Security Configuration and Analysis snap-in and import your Security Template from the file Spooler User Rights.inf.
Apply this template by selecting Configure Computer Now option from the context menu.
Now you check that the user can allow manage the Print Spooler service under non-admin account.
How to Grant Users Rights to Manage a Service using GPO?
If you have to grant permissions to users to start/stop a service multiple servers or domain computer, it’s easier to use Group Policy (GPO) features:
- Create a new GPO or edit the existing one, link it to the necessary Active Directory container (OU) with the computer objects . Go to the policy section Computer configuration -> Windows Settings -> Security Settings -> System Services;
- Find the Spooler service and grant permissions to the users like in the method described above. Save the changes;
The security settings for all services for which you changed the default permissions are stored in their own registry key HKLM\System\CurrentControlSet\Services\ \Security in the Security parameter of the REG_BINARY type.
This means that one of the ways to set service permissions on other computers is to export/import this registry parameter (including through a GPO).
So, we looked at several ways to manage the Windows service permissions, which allow you to grant any permissions for system services to non-admin user. If the user requires remote access to the service, without granting it local logon or RDP access permissions, you must allow the user to connect remotely and enumerate services via Service Control Manager.
Start or stop Windows service from command line (CMD)
We normally use Services.msc to start or stop or disable or enable any service. We can do the same from windows command line also using net and sc utilities. Below are commands for controlling the operation of a service.
Command to stop a service:
To start a service:
You need to have administrator privileges to run net start/stop commands. If you are just a normal user on the computer, you would get an error like below.
To disable a service:
To enable a service:
To make a service start automatically with system boot:
Note: Space is mandatory after ‘=’ in the above sc commands.
This SC command works on a Windows 7 machine and also on the down-level editions of Windows i.e Windows XP/2003 and Windows Vista. Again, if you do not have administrator previliges you would get the below error.
Note that the service name is not the display name of a service. Each service is given a unique identification name which can be used with net or sc commands. For example, Remote procedure call (RPC) is the display name of the service. But the service name we need to use in the above commands is RpcSs.
So to start Remote procedure call service the command is:
These service names are listed below for each service. The first column shows the display name of a service and the second column shows the service name that should be used in net start or net stop or sc config commands.
Практическое руководство. Запуск служб How to: Start Services
Установленную службу необходимо запустить. After a service is installed, it must be started. Процедура запуска вызывает метод OnStart в классе службы. Starting calls the OnStart method on the service class. Как правило, метод OnStart определяет полезные действия, которые будет выполнять служба. Usually, the OnStart method defines the useful work the service will perform. Запущенная служба остается активной, пока не будет приостановлена или остановлена вручную. After a service starts, it remains active until it is manually paused or stopped.
Службы можно настроить на запуск автоматически или вручную. Services can be set up to start automatically or manually. Служба, которая запускается автоматически, будет запущена при первом включении или перезагрузке компьютера, на котором она установлена. A service that starts automatically will be started when the computer on which it is installed is rebooted or first turned on. Службу, которая запускается вручную, должен запустить пользователь. A user must start a service that starts manually.
По умолчанию службы, созданные с помощью Visual Studio, настроены на запуск вручную. By default, services created with Visual Studio are set to start manually.
Есть несколько способов запуска службы вручную: из диспетчера служб или обозревателя сервера либо из кода, используя компонент, который называется ServiceController. There are several ways you can manually start a service — from Server Explorer, from the Services Control Manager, or from code using a component called the ServiceController.
Вы можете задать свойство StartType в классе ServiceInstaller, чтобы определить способ запуска службы — вручную или автоматически. You set the StartType property on the ServiceInstaller class to determine whether a service should be started manually or automatically.
Настройка способа запуска службы To specify how a service should start
Создав службу, добавьте для нее необходимые установщики. After creating your service, add the necessary installers for it. Дополнительные сведения см. в разделе Практическое руководство. Добавление установщиков в приложение-службу. For more information, see How to: Add Installers to Your Service Application.
В конструкторе щелкните установщик процессов службы, с которой вы работаете. In the designer, click the service installer for the service you are working with.
В окне свойств задайте свойству StartType одно из следующих значений: In the Properties window, set the StartType property to one of the following:
Чтобы установить службу To have your service install | Задайте это значение Set this value |
---|---|
При перезапуске компьютера When the computer is restarted | Автоматический Automatic |
При запуске службы с помощью явного действия пользователя When an explicit user action starts the service | Manual (Вручную) Manual |
Чтобы полностью запретить запуск службы, можно задать свойству StartType значение Disabled (Отключено). To prevent your service from being started at all, you can set the StartType property to Disabled. Это можно сделать, если вы собираетесь перезагружать сервер несколько раз и хотите сэкономить время, запретив запуск служб, которые обычно запускаются одновременно. You might do this if you are going to reboot a server several times and want to save time by preventing the services that would normally start from starting up.
Эти и другие свойства можно изменить после установки службы. These and other properties can be changed after your service is installed.
Есть несколько способов запуска службы, для процесса StartType которой настроено значение Manual (Вручную): из диспетчера служб или обозревателя серверов либо из кода. There are several ways you can start a service that has its StartType process set to Manual — from Server Explorer, from the Windows Services Control Manager, or from code. Важно отметить, что в действительности не все эти методы приводят к запуску службы в контексте диспетчера служб. При использовании обозревателя сервера и программных способов применяется контроллер. It is important to note that not all of these methods actually start the service in the context of the Services Control Manager; Server Explorer and programmatic methods of starting the service actually manipulate the controller.
Запуск службы вручную из обозревателя сервера To manually start a service from Server Explorer
В обозревателе сервера добавьте нужный сервер, если его нет в списке. In Server Explorer, add the server you want if it is not already listed. Дополнительные сведения см. в разделах «Практическое руководство. Подключение и инициализация обозревателя серверов или обозревателя баз данных». For more information, see How to: Access and Initialize Server Explorer-Database Explorer.
Разверните узел Службы и выберите службу, которую нужно запустить. Expand the Services node, and then locate the service you want to start.
Щелкните службу правой кнопкой мыши и выберите команду Запустить. Right-click the name of the service, and click Start.
Запуск службы вручную из диспетчера служб To manually start a service from Services Control Manager
Откройте диспетчер служб, сделав следующее: Open the Services Control Manager by doing one of the following:
В Windows XP и 2000 Professional щелкните правой кнопкой мыши значок Мой компьютер на рабочем столе и выберите Управление. In Windows XP and 2000 Professional, right-click My Computer on the desktop, and then click Manage. В открывшемся диалоговом окне разверните узел Службы и приложения. In the dialog box that appears, expand the Services and Applications node.
В Windows Server 2003 и Windows 2000 Server нажмите кнопку Пуск, выберите Программы, Администрирование и Службы. In Windows Server 2003 and Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
В Windows NT версии 4.0 можно открыть это диалоговое окно на панели управления. In Windows NT version 4.0, you can open this dialog box from Control Panel.
Теперь ваша служба должна отобразиться в списке Службы. You should now see your service listed in the Services section of the window.
Выберите службу в списке, щелкните ее правой кнопкой мыши и нажмите кнопку Запустить. Select your service in the list, right-click it, and then click Start.
Запуск службы вручную из кода To manually start a service from code
Создайте экземпляр класса ServiceController и настройте его для взаимодействия со службой, которой нужно управлять. Create an instance of the ServiceController class, and configure it to interact with the service you want to administer.
Чтобы запустить службу, вызовите метод Start. Call the Start method to start the service.