Windows services management tool

Windows Service Manager (SrvMan)

Windows Service Manager is a small tool that simplifies all common tasks related to Windows services. It can create services (both Win32 and Legacy Driver) without restarting Windows, delete existing services and change service configuration. It has both GUI and Command-line modes. It can also be used to run arbitrary Win32 applications as services (when such service is stopped, main application window is closed automatically).

Features

Here is a list of SrvMan’s key features:

Allows creating driver and Win32 services without restarting.

Supports both GUI and Command Line.

Supports all modern 32-bit and 64-bit versions of Windows

Allows running arbitrary Win32 applications as services.

Allows installing & running legacy driver services in a single command line call.

SrvMan — Command Line Options

You can use SrvMan’s Command Line interface to perform the following tasks:

Install & start a legacy driver with a single call

Note that when you run SrvMan with command-line arguments from non-console application (for example, from a Run dialog box), it displays the «Press any key to continue. » message and pauses just before exiting. This does not happen, when SrvMan is run from a console application (such as cmd.exe). To override this behavior, use the /pause:no switch.

Creating services

Use the following command line to create services using SrvMan (parameters in brackets are optional):

Service name is an internal name used by Windows to reference the service. Display name is the name displayed in Windows Services snap-in. By default, both names are generated from the .exe or .sys file name, however, you can override it by specifying names explicitly.

Service type can be one of the following:

  • drv — Create a kernel driver (selected by default for .sys files)
  • exe — Create a Win32 service (selected by default for .exe files)
  • sharedexe — Create a Win32 service with shared executable file
  • fsd — Create a file system driver service
  • app — Create a service running ordinary windows application (such as taskmgr.exe)

Start mode is one of the following:

  • boot — The service is started by OS loader
  • sys — The service is started by IoInitSystem() call
  • auto — The service is started by Service Control Manager during startup
  • man — The service is started manually (net start/net stop)
  • dis — The service cannot be started

Win32 services are created as interactive by default. To create a non-interactive service, you should specify the /interactive:no parameter. Normally, if a specified service already exists, SrvMan reports an error and stops. However, if you specify the /overwrite:yes parameter, an existing service will be overwritten instead.

Deleting services

Deleting services using SrvMan command line is quite obvious:

Note that you need to specify the internal service name (same as used for net start command), not the display name.

Starting/stopping/restarting services

You can control all types of services using SrvMan command line:

Normally, SrvMan waits for the service to start. However, if you specify the /nowait parameter, SrvMan will return control immediately after the start/stop request was issued. Note that if you need SrvMan to wait before starting/stopping the service (for example, to switch to real-time log viewer window), you can use the /delay: parameter.

Testing legacy drivers

You can easily test your legacy driver by using the following command line:

This command creates (or overwrites) a service for a given legacy driver file and starts it. If you have specified the /copy:yes switch, the driver file will be copied to system32\drivers directory. If /overwrite:no is specified, DbgMan will return an error if the service (or the driver file in system32\drivers) already exists. If /after: is specified, the driver will be stopped msec milliseconds after successful start. You can use this switch to test driver load/unload cycle.

Downloading

The latest version of SrvMan for both x86 and x64 systems (including sources) can be downloaded here. Note that you need BazisLib library to build the sources.

Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services

Если вы разрабатываете службу Windows с помощью .NET Framework, вы можете быстро установить приложение службы с помощью служебной программы командной строки InstallUtil.exe или PowerShell. If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Если вы являетесь разработчиком и хотите создать службу Windows, которую пользователи могут устанавливать и удалять, можно использовать набор инструментов WiX или коммерческие средства, такие как Advanced Installer, InstallShield или другие. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. См. сведения о создании пакета установщика (классическое приложение Windows). For more information, see Create an installer package (Windows desktop).

Читайте также:  Windows не видит принтер подключенный через usb

Если вы хотите удалить службу на своем компьютере, не выполняйте процедуру, описанную в этой статье. If you want to uninstall a service from your computer, don’t follow the steps in this article. Вместо этого определите, какая программа (или программный пакет) установила эту службу, а затем выберите Приложения в параметрах, чтобы удалить эту программу. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Следует отметить, что многие службы являются составной частью ОС Windows. Если их удалить, это может привести к нестабильной работе системы. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.

Чтобы использовать процедуру, описанную в этой статье, сначала необходимо добавить установщик службы в свою службу Windows. To use the steps in this article, you first need to add a service installer to your Windows service. Дополнительные сведения см. в разделе Пошаговое руководство: создание диспетчера служб Windows. For more information, see Walkthrough: Creating a Windows service app.

Проекты служб Windows нельзя запускать непосредственно из среды разработки Visual Studio путем нажатия клавиши F5. You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Перед запуском проекта необходимо установить службу в проекте. Before you can run the project, you must install the service in the project.

Запустите обозреватель сервера и убедитесь, что служба установлена или удалена. You can use Server Explorer to verify that you’ve installed or uninstalled your service.

Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility

В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .

Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.

Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.

Запустите InstallUtil.exe из командной строки, указав исполняемый файл проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:

Если вы используете командную строку разработчика для Visual Studio, системный путь должен указывать на файл InstallUtil.exe. If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Если это не так, можно добавить его в путь или использовать полный путь для его вызова. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. Этот инструмент устанавливается вместе с платформой .NET Framework в папку %WINDIR%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .

Пример: For example:

  • Для 32-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: если каталог установки Windows — C:\Windows, по умолчанию используется путь C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe. For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
  • Для 64-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: по умолчанию используется путь C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe. For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.

Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility

В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .

Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.

Запустите InstallUtil.exe из командной строки, указав выходные данные проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s output as a parameter:

После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.

Читайте также:  Routersploit kali linux ���������

Установка с помощью PowerShell Install using PowerShell

В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.

Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.

Выполните командлет New-Service, указав в качестве параметров выходные данные проекта и имя службы. Run the New-Service cmdlet with the with your project’s output and a service name as parameters:

Удаление с помощью PowerShell Uninstall using PowerShell

В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.

Выполните командлет Remove-Service, указав в качестве параметра имя службы. Run the Remove-Service cmdlet with the name of your service as parameter:

После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.

Introduction to Windows Service Applications

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. For more information about services and Windows sessions, see the Windows SDK documentation.

You can easily create services by creating an application that is installed as a service. For example, suppose you want to monitor performance counter data and react to threshold values. You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service’s executable file. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

Service Applications vs. Other Visual Studio Applications

Service applications function differently from many other project types in several ways:

The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. Instead, you must install and start your service, and then attach a debugger to the service’s process. For more information, see How to: Debug Windows Service Applications.

Unlike some types of projects, you must create installation components for service applications. The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. For more information, see How to: Add Installers to Your Service Application.

The Main method for your service application must issue the Run command for the services your project contains. The Run method loads the services into the Services Control Manager on the appropriate server. If you use the Windows Services project template, this method is written for you automatically. Note that loading a service is not the same thing as starting the service. See «Service Lifetime» below for more information.

Windows Service applications run in a different window station than the interactive station of the logged-on user. A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

Читайте также:  Не работает боковая панель windows

The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. The .NET Framework also does not include classes that represent stations and desktops. If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. For more information, see the Windows SDK documentation.

The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

Service Lifetime

A service goes through several internal states in its lifetime. First, the service is installed onto the system on which it will run. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. The Services Control Manager is the central utility provided by Windows to administer services.

After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. The Start method passes processing to the application’s OnStart method and processes any code you have defined there.

A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped. The service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

Types of Services

There are two types of services you can create in Visual Studio using the .NET Framework. Services that are the only service in a process are assigned the type Win32OwnProcess. Services that share a process with another service are assigned the type Win32ShareProcess. You can retrieve the service type by querying the ServiceType property.

You might occasionally see other service types if you query existing services that were not created in Visual Studio. For more information on these, see the ServiceType.

Services and the ServiceController Component

The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. However, you do not need to use a ServiceController component when you create a service application. In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

For more information, see ServiceController.

Requirements

Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

Projects containing Windows services must have installation components for the project and its services. This can be easily accomplished from the Properties window. For more information, see How to: Add Installers to Your Service Application.

Оцените статью