Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Низкоуровневое программирование > Win Api
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 23.10.2009, 06:13   #1
SanekIrk
Пользователь
 
Аватар для SanekIrk
 
Регистрация: 10.07.2008
Сообщений: 87
Лампочка Остановка служб.

Хочу автоматизировать настройку WinXP. Каким образом можно отключить интересующую меня службу?

Выяснил, что список можно получить из реестра, а отключить через него че то не получается.

Последний раз редактировалось SanekIrk; 23.10.2009 в 06:28.
SanekIrk вне форума Ответить с цитированием
Старый 23.10.2009, 08:53   #2
Пепел Феникса
Старожил
 
Аватар для Пепел Феникса
 
Регистрация: 28.01.2009
Сообщений: 21,000
По умолчанию

сча накидаю фунок нужных
Цитата:
The OpenSCManager function establishes a connection to the service control manager on the specified computer and opens the specified database.

SC_HANDLE OpenSCManager(

LPCTSTR lpMachineName, // pointer to machine name string //пустая строка локальный комп
LPCTSTR lpDatabaseName, // pointer to database name string //тут тоже можно пустоту передать(nil)
DWORD dwDesiredAccess // type of access
);


Parameters

lpMachineName

Points to a null-terminated string that names the target computer. If the pointer is NULL or if it points to an empty string, the function connects to the service control manager on the local computer.

lpDatabaseName

Points to a null-terminated string that names the service control manager database to open. This string should specify ServicesActive. If the pointer is NULL, the ServicesActive database is opened by default.

dwDesiredAccess

Specifies the access to the service control manager. Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service control manager object. The SC_MANAGER_CONNECT access type is implicitly specified by calling this function. In addition, any or all of the following service control manager object access types can be specified:

Type Description
SC_MANAGER_ALL_ACCESS
Includes STANDARD_RIGHTS_REQUIRED, in addition to all of the access types listed in this table.
SC_MANAGER_CONNECT
Enables connecting to the service control manager.
SC_MANAGER_CREATE_SERVICE
Enables calling of the CreateService function to create a service object and add it to the database.
SC_MANAGER_ENUMERATE_SERVICE
Enables calling of the EnumServicesStatus function to list the services that are in the database.
SC_MANAGER_LOCK
Enables calling of the LockServiceDatabase function to acquire a lock on the database.
SC_MANAGER_QUERY_LOCK_STATUS
Enables calling of the QueryServiceLockStatus function to retrieve the lock status information for the database.


The dwDesiredAccess parameter can specify any or all of the following generic access types:

Generic access Service manager access
GENERIC_READ Combines the following access: STANDARD_RIGHTS_READ, SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS.
GENERIC_WRITE Combines the following access: STANDARD_RIGHTS_WRITE, SC_MANAGER_CREATE_SERVICE, and SC_MANAGER_MODIFY_BOOT_CONFIG.
GENERIC_EXECUTE Combines the following access: STANDARD_RIGHTS_EXECUTE, SC_MANAGER_CONNECT, and SC_MANAGER_LOCK.


Return Values

If the function succeeds, the return value is a handle to the specified service control manager database.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Error code Meaning
ERROR_ACCESS_DENIED The requested access was denied.
ERROR_DATABASE_DOES_NOT_EXIST The specified database does not exist.
ERROR_INVALID_PARAMETER A parameter that was specified is invalid.


Remarks

When a process uses the OpenSCManager function to open a handle to a service control manager database, the system performs a security check before granting the requested access. All processes are permitted SC_MANAGER_CONNECT, SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS access to all service control manager databases. This enables any process to open a service control manager database handle that it can use in the OpenService, EnumServicesStatus, and QueryServiceLockStatus functions. Only processes with Administrator privileges are able to open a database handle used by the CreateService and LockServiceDatabase functions.

The calling process can use the returned handle to identify the database in the following functions, if the appropriate access rights are enabled:
CreateService
EnumServicesStatus
LockServiceDatabase
OpenService
QueryServiceLockStatus
The returned handle is only valid for the process that called the OpenSCManager function. It can be closed by calling the CloseServiceHandle function.
Хорошо поставленный вопрос это уже половина ответа. | Каков вопрос, таков ответ.
Программа делает то что написал программист, а не то что он хотел.
Функции/утилиты ждут в параметрах то что им надо, а не то что вы хотите.
Пепел Феникса вне форума Ответить с цитированием
Старый 23.10.2009, 08:55   #3
Пепел Феникса
Старожил
 
Аватар для Пепел Феникса
 
Регистрация: 28.01.2009
Сообщений: 21,000
По умолчанию

Цитата:
The OpenService function opens a handle to an existing service.

SC_HANDLE OpenService(

SC_HANDLE hSCManager, // handle to service control manager database
LPCTSTR lpServiceName, // pointer to name of service to start //если такого сервиса нет, то функция не вернет коректного хендла.
DWORD dwDesiredAccess // type of access to service
);


Parameters

hSCManager

Identifies the service control manager (SCM) database. The OpenSCManager function returns this handle.

lpServiceName

Points to a null-terminated string that names the service to open. The maximum string length is 256 characters. The SCM database preserves the case of the characters, but service name comparisons are always case insensitive. A slash (/), backslash (\), comma, and space are invalid service name characters.

dwDesiredAccess

Specifies the access to the service. Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service object. Any or all of the following service object access types can be specified:

Access Description
SERVICE_ALL_ACCESS Includes STANDARD_RIGHTS_REQUIRED in addition to all of the access types listed in this table.
SERVICE_CHANGE_CONFIG Enables calling of the ChangeServiceConfig function to change the service configuration.
SERVICE_ENUMERATE_DEPENDENTS Enables calling of the EnumDependentServices function to enumerate all the services dependent on the service.
SERVICE_INTERROGATE Enables calling of the ControlService function to ask the service to report its status immediately.
SERVICE_PAUSE_CONTINUE Enables calling of the ControlService function to pause or continue the service.
SERVICE_QUERY_CONFIG Enables calling of the QueryServiceConfig function to query the service configuration.
SERVICE_QUERY_STATUS Enables calling of the QueryServiceStatus function to ask the service control manager about the status of the service.
SERVICE_START Enables calling of the StartService function to start the service.
SERVICE_STOP Enables calling of the ControlService function to stop the service.
SERVICE_USER_DEFINED_CONTROL Enables calling of the ControlService function to specify a user-defined control code.


STANDARD_RIGHTS_REQUIRED enables the following service object access types:

Standard rights Description
DELETE Enables calling of the DeleteService function to delete the service.
READ_CONTROL Enables calling of the QueryServiceObjectSecurity function to query the security descriptor of the service object.
WRITE_DAC|WRITE_OWNER Enables calling of the SetServiceObjectSecurity function to modify the security descriptor of the service object.


The dwDesiredAccess parameter can specify any or all of the following generic access types:

Generic access Service access
GENERIC_READ Combines the following access: STANDARD_RIGHTS_READ, SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS, SERVICE_INTERROGATE, and SERVICE_ENUMERATE_DEPENDENTS.
GENERIC_WRITE Combines the following access: STANDARD_RIGHTS_WRITE and SERVICE_CHANGE_CONFIG.
GENERIC_EXECUTE Combines the following access: STANDARD_RIGHTS_EXECUTE, SERVICE_START, SERVICE_STOP, SERVICE_PAUSE_CONTINUE, and SERVICE_USER_DEFINED_CONTROL.


Return Values

If the function succeeds, the return value is a handle to the service.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Errors

The following error codes can be set by the service control manager. Others can be set by the registry functions that are called by the service control manager.

Error code Meaning
ERROR_ACCESS_DENIED The specified service control manager database handle does not have access to the service.
ERROR_INVALID_HANDLE The specified handle is invalid.
ERROR_INVALID_NAME The specified service name is invalid.
ERROR_SERVICE_DOES_NOT_EXIST The specified service does not exist.


Remarks

The calling process can use the returned handle to identify the service in the following functions, if the appropriate access rights are enabled:
ChangeServiceConfig
ControlService
DeleteService
EnumDependentServices
QueryServiceConfig
QueryServiceObjectSecurity
QueryServiceStatus
SetServiceObjectSecurity
StartService
The returned handle is only valid for the process that called OpenService. It can be closed by calling the CloseServiceHandle function.
перечисление всех сервисов я думаю не нужно?
Хорошо поставленный вопрос это уже половина ответа. | Каков вопрос, таков ответ.
Программа делает то что написал программист, а не то что он хотел.
Функции/утилиты ждут в параметрах то что им надо, а не то что вы хотите.
Пепел Феникса вне форума Ответить с цитированием
Старый 23.10.2009, 08:56   #4
Пепел Феникса
Старожил
 
Аватар для Пепел Феникса
 
Регистрация: 28.01.2009
Сообщений: 21,000
По умолчанию

Цитата:
The ControlService function sends a control code to a Win32 service.

BOOL ControlService(

SC_HANDLE hService, // handle to service
DWORD dwControl, // control code
LPSERVICE_STATUS lpServiceStatus // pointer to service status structure
);


Parameters

hService

Identifies the service. This handle is returned by the OpenService or CreateService function. The access required for this handle depends on the dwControl code requested.

dwControl

Specifies the requested control code. This value can be one of the standard control codes in the table, or it can be a user-defined control code in the range of 128 to 255, inclusive. For user-defined control codes, the hService handle must have SERVICE_USER_DEFINED_CONTROL access, and the service defines the action associated with the control code.

Value Meaning
SERVICE_CONTROL_STOP
Requests the service to stop. The hService handle must have SERVICE_STOP access.
SERVICE_CONTROL_PAUSE
Requests the service to pause. The hService handle must have SERVICE_PAUSE_CONTINUE access.
SERVICE_CONTROL_CONTINUE
Requests the paused service to resume. The hService handle must have SERVICE_PAUSE_CONTINUE access.
SERVICE_CONTROL_INTERROGATE
Requests the service to update immediately its current status information to the service control manager. The hService handle must have SERVICE_INTERROGATE access.
SERVICE_CONTROL_SHUTDOWN
The ControlService function fails if this control code is specified.


lpServiceStatus

Points to a SERVICE_STATUS structure where the latest status information of the service is returned. The information returned reflects the most recent status reported by the service to the service control manager.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value Meaning
ERROR_ACCESS_DENIED
The specified handle was not opened with the necessary access.
ERROR_DEPENDENT_SERVICES_RUNNING
The service cannot be stopped because other running services are dependent on it.
ERROR_INVALID_SERVICE_CONTROL
The requested control code is not valid, or it is unacceptable to the service.
ERROR_SERVICE_CANNOT_ACCEPT_CTRL
The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.
ERROR_SERVICE_NOT_ACTIVE
The service has not been started.
ERROR_SERVICE_REQUEST_TIMEOUT
The service did not respond to the start request in a timely fashion.


Remarks

The ControlService function asks the service control manager to send the requested control code to the service. The service control manager sends the code if the service accepts the control and if the service is in a controllable state. The QueryServiceStatus or ControlService function returns a SERVICE_STATUS structure whose dwCurrentState and dwControlsAccepted members indicate the current state and controls accepted by a running Win32 service.

All running services accept the SERVICE_CONTROL_INTERROGATE control code by default. Each service specifies the other control codes that it accepts when it calls the SetServiceStatus function to report its status.
The following table shows the action of the service control manager in each of the possible service states:

Service state Stop Other controls
STOPPED (c) (c)
STOP_PENDING (b) (b)
START_PENDING (a) (b)
RUNNING (a) (a)
CONTINUE_PENDING (a) (a)
PAUSE_PENDING (a) (a)
PAUSED (a) (a)


(a) If the service accepts this control code, send the request to the service; otherwise, ControlService returns FALSE and GetLastError returns ERROR_INVALID_SERVICE_CONTROL.
(b) The service is not in a controllable state, so ControlService returns FALSE and GetLastError returns ERROR_SERVICE_CANNOT_ACCEPT_CTRL.
(c) The service is not in a controllable state, so ControlService returns FALSE and GetLastError returns ERROR_SERVICE_NOT_ACTIVE.
осталось еще несколько.
Хорошо поставленный вопрос это уже половина ответа. | Каков вопрос, таков ответ.
Программа делает то что написал программист, а не то что он хотел.
Функции/утилиты ждут в параметрах то что им надо, а не то что вы хотите.
Пепел Феникса вне форума Ответить с цитированием
Старый 23.10.2009, 08:58   #5
Пепел Феникса
Старожил
 
Аватар для Пепел Феникса
 
Регистрация: 28.01.2009
Сообщений: 21,000
По умолчанию

Цитата:
The CloseServiceHandle function closes a handle to a service control manager database as returned by the OpenSCManager function, or it closes a handle to a service object as returned by either the OpenService or CreateService function.

BOOL CloseServiceHandle(

SC_HANDLE hSCObject // handle to service or service control manager database
);


Parameters

hSCObject

Identifies the service control manager database or the service object to close.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Errors

The following error code may be set by the service control manager. Other error codes may be set by registry functions that are called by the service control manager.

Value Meaning
ERROR_INVALID_HANDLE The specified handle is invalid.


Remarks

The CloseServiceHandle function does not destroy the service control manager object referred to by the handle. A service control manager object cannot be destroyed. A service object can be destroyed by calling the DeleteService function.
ну и закрытие хендла.
минимум есть..
Хорошо поставленный вопрос это уже половина ответа. | Каков вопрос, таков ответ.
Программа делает то что написал программист, а не то что он хотел.
Функции/утилиты ждут в параметрах то что им надо, а не то что вы хотите.
Пепел Феникса вне форума Ответить с цитированием
Старый 23.10.2009, 13:37   #6
Баламут
Баламучу слегка...
Участник клуба
 
Аватар для Баламут
 
Регистрация: 01.11.2006
Сообщений: 1,585
По умолчанию

Теория это, конечно же хорошо. Я и сам постоянный читатель MSDN. Но, я так думаю, человеку явно не знакомому с темой и при этом программирующем на Делфи трудно будет разобраться с исходником на С да еще и с не совсем русскими комментариями...
В общем в свое время я писал для этих целей класс, который и предлагаю вместе с примером, решающим поставленную задачу. Но сразу хочу предупредить, что для этого еще нужны библиотеки из Jedi API. В архиве они тоже присутствуют.
Вложения
Тип файла: rar forum.rar (2.07 Мб, 20 просмотров)
Баламут вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Остановка перемещение картиники Ruska882009 Помощь студентам 0 06.04.2009 14:03
Конфигуратор служб Баламут Софт 3 18.03.2009 01:54
Немедленная остановка потока. Altera Общие вопросы Delphi 16 07.02.2009 11:17
Остановка Memo Sanek777 Общие вопросы Delphi 1 11.09.2008 15:50
клиент служб терминалов Рустам Софт 0 31.05.2008 15:14