- Start or stop Windows service from command line (CMD)
- Cannot Start Windows Service in NetworkService account
- 3 Answers 3
- Windows — Use Local Service and/or Network Service account for a windows service
- 3 Answers 3
- How do I ‘run as’ ‘Network Service’?
- 5 Answers 5
- Пишем свой Windows service
- Шаг 1. Создание проекта.
- Шаг 2. Добавление установщика.
- Шаг 3. Логирование.
- Шаг 4. Установка.
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.
Cannot Start Windows Service in NetworkService account
I have a windows service project implementation that I am trying to install as network service.
however whenever I try to start the service I get :
This comes after running the net start MyService command in the visual studio command prompt which is running as administrator by the way.
Any help on how to get this to work? Thanks.
3 Answers 3
I would check that the Network Service account has permissions to execute. Steps to check:
- In Windows explorer go to the folder containing the binaries of the service
- Right-click on the folder > Properties > Security tab > Edit button
- Add > «NETWORK SERVICE» > OK
- Give it full control (just to test and then reduce permissions till it working)
Your Net Start MyService is probably not running with escalated privileges. Your command requires (I believe) Administrative Privileges.
Update
Not sure why, but your privileges on your service are weird. By default privileges of services should look like:
However your’s looks like:
I’m not sure exactly how that came to be. Try uninstalling and reinstalling?
You can download SddlParse (google it 🙂 to parse out the Security Descriptor Definition Language.
Windows — Use Local Service and/or Network Service account for a windows service
I’ve created a window’s service that monitors files on a specific directory on our Windows OS. When a file is detected, the service does some file I/O, reads the files, creates sub-directories, etc. This service also uses database connectivity to connect to another server. My plan is to have the service run as the default «Local Service» account. Since I need to allow write/read privileges, which apparently the «Local Service» account does not do by default, I’m going to explicitly set «Full Control» privileges for the «Local Service» account on the folder that I’m reading/writing to and from.
I believe the above is a good . My question is, for the folder that I’m reading and writing to, do I need to setup a «Network Service» role with full control access? I’m wondering since my service uses database connectivity to another server, if I’ll need the «Network Service» account setup.
I may be misunderstanding what the «Network Service» account does.
3 Answers 3
The NT AUTHORITY\NetworkService account is only needed when you’re communicating with other computers in a domain that need your machine’s credentials for access control. It is not required for simple Internet/network access. It is only necessary for specific purposes in an Active Directory domain.
Also the entire point of the NT AUTHORITY\LocalService account is that it has minimum privileges on the system. Giving it more privileged decreases the security of the many services on your system designed to run at the low privilege level it was designed to proffer. If your service requires privileges above and beyond those, you should create a new account for it with the necessary privileges and set that account in the Log On tab of the service’s properties. (This can also be done programatically.)
You could also run it using the NT AUTORITY\LocalSystem account, which has unlimited access to your system, but I assume you wanted to use the LocalService account for the increased security it provides.
The other answers confirm what you say about using Local Service. To summarize, Local Service is the recommended account to use with your service, unless you need the extra Active Directory SSPI features of Network Service.
For restricting read/write access to a specific folder, you can do better than just giving access to the generic Local Service account though. The problem, as others have pointed out, is that this would also give read/write access to all other services running as Local Service and if all services did this then gradually Local Service would receive access to more and more important resources.
The solution is to instead ACL your folder using your specific service SID. Only your own service process has your service SID associated with it, so this locks down your resource even further. You can view the service SID using sc showsid . The service SID is generated from the service name, so it will be the same on all machines.
To enable service SID usage by your service, use ChangeServiceConfig2 with the SERVICE_SID_INFO structure to set SERVICE_SID_TYPE_UNRESTRICTED . You can also set SERVICE_SID_TYPE_RESTRICTED to get an even more restricted SID that only allows write access to resources explicitly allowed with your service SID.
The previous answer didn’t appear to address the questions directly, so I thought I would add to it.
- My plan is to have the service run as the default «Local Service» account. I’m going to explicitly set «Full Control» privileges for the «Local Service» account on the folder that I’m reading/writing to and from. I believe the above is a good plan.
Personally, I don’t see a big issue with this plan. With BUILTINs, the choice is between:
- Running as LOCALSYSTEM — so if this service is compromised, the attacker owns Everything, and immediately.
- Running as LOCALSERVICE — so if this service, or any of the many other services running under this account, are compromised, the attacker has access to one extra directory.*
Arguably, adding a few extra ACLs to be able to use the second option is preferable. Yes, the safest option for a low-privilege but highly security-sensitive service would be to run under a custom tailored, low privilege service account. But unless you want to create a new account/manage passwords for every service you deploy, using LocalService for minor non-sensitive tasks is not such a terrible thing. You just need to make a responsible decision based on these considerations, like what is in that directory or that database, impact if they are breached etc.
Although again, per least privilege principle, you should only set Full Control if Modify is really not sufficient.
2.My question is, for the folder that I’m reading and writing to, do I need to setup a «Network Service» role with full control access? I’m wondering since my service uses database connectivity to another server, if I’ll need the «Network Service» account setup.
If your database required Windows Integrated/SSPI login, then yes, you would need to use NetworkService (or a domain service account) everywhere, i.e., RunAs and directory permissions. Assuming you also granted your computername$ or domain account access to this database. I doubt you are doing that, so if it uses normal username/pwd authentication, you should be able to do everything with LocalService. You need to grant only one account rights on that directory, whichever you use in your RunAs, not both.
3.I may be misunderstanding what the «Network Service» account does.
LocalService/NetworkService are almost identical accounts on the local computer. The difference mainly is what they can do on the network. NS can access some network resources because it appears on the network as a real (computer) account. But LS will appear as ANONYMOUS, so it will be denied mostly everything on the network.
By the way, you should be using a Scheduled Task for this, not a service.
*From Vista onwards, due to service isolation, one compromised LocalService process cannot easily attack another. Each LocalService/NetworkService service process/instance gets its own unique logon session SID (unique owner), unlike Windows 2003. But I’m not sure this is perfect and fully mitigates the DACL vulnerability on files and resources. Restricted SIDs and write-restricted tokens are mentioned in this context.
How do I ‘run as’ ‘Network Service’?
I am trying to run a process as another account. I have the command:
but then this asks for the password. However there is no password set for the network service.
Is what I am trying to do possible?
5 Answers 5
Use PsExec.exe from SysInternals, running from an elevated command prompt.
e.g. this will open a new command prompt running as NETWORK SERVICE:
this will run it as LOCAL SYSTEM:
You can verify these by running whoami from the cmd prompt.
In Task Scheduler, create a task to run the application under the NETWORK SERVICE user. You can then run the task from the command line using
Where taskname is the name of your task.
You can only impersonate as service account from a Windows service typically, like this post mentions:
The trick is to run your code as Local System and from there you can impersonate the service accounts by using the appropriate username with no password. One way to run your code as the Local System account is to create a command line shell by using the technique shown below (taken from this orginal post), and execute your assembly from there. Calling System.Diagnostics.Debugger.Break() in your code allows you to debug.
To create a command-line shell that runs under the local system account, open a new command line window and enter:
A new command window should have opened up. In that window run your application.exe — you’ll see that you’re now running as the built-in System user account. After you’ve finished testing, you can delete the test service you created by entering:
If you try to do that in your own user context, then such attempts should fail.
Пишем свой Windows service
Многие из нас сталкиваются с такой задачей, когда нужно запускать своё приложение при запуске компьютера. Конечно можно поместить ярлык в автозагрузку, но как-то это неправильно. Да к тому же если комп перегрузился, а пользователь не залогинелся, то и ваше приложение тоже не запустится.
Самым верным решением в данной ситуации является написание Windows сервиса.
Пример создания сервиса в Studio 2010, .Net C# под катом
Шаг 1. Создание проекта.
Создайте новый проект, выбрав шаблон Windows Service
Переименуйте класс сервиса как вам нужно.
Получили такой вод код:
namespace ExampleSrv
<
public partial class MyService : ServiceBase
<
public MyService()
<
InitializeComponent();
>
protected override void OnStart( string [] args)
<
>
protected override void OnStop()
<
>
>
>
* This source code was highlighted with Source Code Highlighter .
Это и есть, собственно, сам сервис.
Используйте OnStart и OnStop события для реализации своей поставленной задачи.
Шаг 2. Добавление установщика.
Чтобы ваш сервис заставить работать, его нужно установить.
Чтобы его установить, он должен иметь установщик.
Клик правой кнопкой… Add installer
Теперь у нас есть serviceProcessInstaller и serviceInstaller
В первом можете поставить значение Account в LocalSystem.
Во втором укажите имя сервиса, описание и не забудьте поставить StartType — Automatic.
Шаг 3. Логирование.
Для того чтобы вы смогли узнать что делал ваш сервис, когда он стартовал, завершался или что-нибудь еще, вы можете использовать системное логирование.
Делается это очень легко.
Перетаскиваете из Toolbox в свой сервис EventLog.
Примерно так делается логирование:
public partial class MyService : ServiceBase
<
public MyService()
<
InitializeComponent();
>
protected override void OnStart( string [] args)
<
AddLog( «start» );
>
protected override void OnStop()
<
AddLog( «stop» );
>
public void AddLog( string log)
<
try
<
if (!EventLog.SourceExists( «MyExampleService» ))
<
EventLog.CreateEventSource( «MyExampleService» , «MyExampleService» );
>
eventLog1.Source = «MyExampleService» ;
eventLog1.WriteEntry(log);
>
catch <>
>
>
* This source code was highlighted with Source Code Highlighter .
Шаг 4. Установка.
Чтобы установить сервис, нужно вызвать утилиту установки и передать параметром путь к своему сервису.
Для этого я создал install.bat такого вида:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\. \ExampleSrv\bin\Debug\ExampleSrv.exe
pause
Если вы выбрали в serviceProcessInstaller значением поля Account — User, то при установке вы должны будете ввести логин и пароль учетной записи, под которой будет запускаться сервис. Внимание! Писать домен перед именем пользователя обязательно!
Запускаем батник обязательно с правами администратора и наблюдаем в конце:
The Commit phase completed successfully.
The transacted install has completed.
Это значит что сервис установлен.
Проверяем:
Пару раз делаем запуск и остановку. Смотрим логи:
Видим когда сервис запускался и останавливался.