Class: Win32::Service
- Inherits:
-
Object
- Object
- Win32::Service
- Extended by:
- Windows::ServiceFunctions, Windows::ServiceStructs
- Defined in:
- lib/win32/service.rb,
lib/win32/windows/version.rb
Overview
The Service class encapsulates services controller actions, such as creating, starting, configuring or deleting services.
Defined Under Namespace
Classes: ConfigStruct, ServiceStruct, StatusStruct
Constant Summary collapse
- MANAGER_ALL_ACCESS =
Includes STANDARD_RIGHTS_REQUIRED, in addition to all other rights
SC_MANAGER_ALL_ACCESS
- MANAGER_CREATE_SERVICE =
Required to call the CreateService function
SC_MANAGER_CREATE_SERVICE
- MANAGER_CONNECT =
Required to connect to the service control manager.
SC_MANAGER_CONNECT
- MANAGER_ENUMERATE_SERVICE =
Required to call the EnumServicesStatusEx function to list services
SC_MANAGER_ENUMERATE_SERVICE
- MANAGER_LOCK =
Required to call the LockServiceDatabase function
SC_MANAGER_LOCK
- MANAGER_MODIFY_BOOT_CONFIG =
Required to call the NotifyBootConfigStatus function
SC_MANAGER_MODIFY_BOOT_CONFIG
- MANAGER_QUERY_LOCK_STATUS =
Required to call the QueryServiceLockStatus function
SC_MANAGER_QUERY_LOCK_STATUS
- ALL_ACCESS =
Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights
SERVICE_ALL_ACCESS
- CHANGE_CONFIG =
Required to call functions that configure existing services
SERVICE_CHANGE_CONFIG
- ENUMERATE_DEPENDENTS =
Required to enumerate all the services dependent on the service
SERVICE_ENUMERATE_DEPENDENTS
- INTERROGATE =
Required to make a service report its status immediately
SERVICE_INTERROGATE
- PAUSE_CONTINUE =
Required to control a service with a pause or resume
SERVICE_PAUSE_CONTINUE
- QUERY_CONFIG =
Required to be able to gather configuration information about a service
SERVICE_QUERY_CONFIG
- QUERY_STATUS =
Required to be ask the SCM about the status of a service
SERVICE_QUERY_STATUS
- START =
Required to call the StartService function to start the service.
SERVICE_START
- STOP =
Required to call the ControlService function to stop the service.
SERVICE_STOP
- USER_DEFINED_CONTROL =
Required to call ControlService with a user defined control code
SERVICE_USER_DEFINED_CONTROL
- KERNEL_DRIVER =
Driver service
SERVICE_KERNEL_DRIVER
- FILE_SYSTEM_DRIVER =
File system driver service
SERVICE_FILE_SYSTEM_DRIVER
- WIN32_OWN_PROCESS =
Service that runs in its own process
SERVICE_WIN32_OWN_PROCESS
- WIN32_SHARE_PROCESS =
Service that shares a process with one or more other services.
SERVICE_WIN32_SHARE_PROCESS
- INTERACTIVE_PROCESS =
The service can interact with the desktop
SERVICE_INTERACTIVE_PROCESS
- DRIVER =
SERVICE_DRIVER
- TYPE_ALL =
SERVICE_TYPE_ALL
- BOOT_START =
A service started automatically by the SCM during system startup
SERVICE_BOOT_START
- SYSTEM_START =
A device driver started by the IoInitSystem function. Drivers only
SERVICE_SYSTEM_START
- AUTO_START =
A service started automatically by the SCM during system startup
SERVICE_AUTO_START
- DEMAND_START =
A service started by the SCM when a process calls StartService
SERVICE_DEMAND_START
- DISABLED =
A service that cannot be started
SERVICE_DISABLED
- ERROR_IGNORE =
Error logged, startup continues
SERVICE_ERROR_IGNORE
- ERROR_NORMAL =
Error logged, pop up message, startup continues
SERVICE_ERROR_NORMAL
- ERROR_SEVERE =
Error logged, startup continues, system restarted last known good config
SERVICE_ERROR_SEVERE
- ERROR_CRITICAL =
Error logged, startup fails, system restarted last known good config
SERVICE_ERROR_CRITICAL
- STOPPED =
Service is not running
SERVICE_STOPPED
- START_PENDING =
Service has received a start signal but is not yet running
SERVICE_START_PENDING
- STOP_PENDING =
Service has received a stop signal but is not yet stopped
SERVICE_STOP_PENDING
- RUNNING =
Service is running
SERVICE_RUNNING
- CONTINUE_PENDING =
Service has received a signal to resume but is not yet running
SERVICE_CONTINUE_PENDING
- PAUSE_PENDING =
Service has received a signal to pause but is not yet paused
SERVICE_PAUSE_PENDING
- PAUSED =
Service is paused
SERVICE_PAUSED
- CONTROL_STOP =
Notifies service that it should stop
SERVICE_CONTROL_STOP
- CONTROL_PAUSE =
Notifies service that it should pause
SERVICE_CONTROL_PAUSE
- CONTROL_CONTINUE =
Notifies service that it should resume
SERVICE_CONTROL_CONTINUE
- CONTROL_INTERROGATE =
Notifies service that it should return its current status information
SERVICE_CONTROL_INTERROGATE
- CONTROL_PARAMCHANGE =
Notifies a service that its parameters have changed
SERVICE_CONTROL_PARAMCHANGE
- CONTROL_NETBINDADD =
Notifies a service that there is a new component for binding
SERVICE_CONTROL_NETBINDADD
- CONTROL_NETBINDREMOVE =
Notifies a service that a component for binding has been removed
SERVICE_CONTROL_NETBINDREMOVE
- CONTROL_NETBINDENABLE =
Notifies a service that a component for binding has been enabled
SERVICE_CONTROL_NETBINDENABLE
- CONTROL_NETBINDDISABLE =
Notifies a service that a component for binding has been disabled
SERVICE_CONTROL_NETBINDDISABLE
- ACTION_NONE =
No action
SC_ACTION_NONE
- ACTION_REBOOT =
Reboot the computer
SC_ACTION_REBOOT
- ACTION_RESTART =
Restart the service
SC_ACTION_RESTART
- ACTION_RUN_COMMAND =
Run a command
SC_ACTION_RUN_COMMAND
- VERSION =
"2.3.2".freeze
Constants included from Windows::ServiceConstants
Windows::ServiceConstants::DELETE, Windows::ServiceConstants::ERROR_FILE_NOT_FOUND, Windows::ServiceConstants::ERROR_INSUFFICIENT_BUFFER, Windows::ServiceConstants::ERROR_MORE_DATA, Windows::ServiceConstants::ERROR_RESOURCE_NAME_NOT_FOUND, Windows::ServiceConstants::ERROR_RESOURCE_TYPE_NOT_FOUND, Windows::ServiceConstants::FORMAT_MESSAGE_FROM_SYSTEM, Windows::ServiceConstants::FORMAT_MESSAGE_IGNORE_INSERTS, Windows::ServiceConstants::IDLE_CONTROL_CODE, Windows::ServiceConstants::INFINITE, Windows::ServiceConstants::NO_ERROR, Windows::ServiceConstants::SC_ACTION_NONE, Windows::ServiceConstants::SC_ACTION_REBOOT, Windows::ServiceConstants::SC_ACTION_RESTART, Windows::ServiceConstants::SC_ACTION_RUN_COMMAND, Windows::ServiceConstants::SC_ENUM_PROCESS_INFO, Windows::ServiceConstants::SC_MANAGER_ALL_ACCESS, Windows::ServiceConstants::SC_MANAGER_CONNECT, Windows::ServiceConstants::SC_MANAGER_CREATE_SERVICE, Windows::ServiceConstants::SC_MANAGER_ENUMERATE_SERVICE, Windows::ServiceConstants::SC_MANAGER_LOCK, Windows::ServiceConstants::SC_MANAGER_MODIFY_BOOT_CONFIG, Windows::ServiceConstants::SC_MANAGER_QUERY_LOCK_STATUS, Windows::ServiceConstants::SC_STATUS_PROCESS_INFO, Windows::ServiceConstants::SERVICE_ACCEPT_HARDWAREPROFILECHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_NETBINDCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_PARAMCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_PAUSE_CONTINUE, Windows::ServiceConstants::SERVICE_ACCEPT_POWEREVENT, Windows::ServiceConstants::SERVICE_ACCEPT_PRESHUTDOWN, Windows::ServiceConstants::SERVICE_ACCEPT_SESSIONCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_SHUTDOWN, Windows::ServiceConstants::SERVICE_ACCEPT_STOP, Windows::ServiceConstants::SERVICE_ACCEPT_TIMECHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_TRIGGEREVENT, Windows::ServiceConstants::SERVICE_ACTIVE, Windows::ServiceConstants::SERVICE_ADAPTER, Windows::ServiceConstants::SERVICE_ALL_ACCESS, Windows::ServiceConstants::SERVICE_AUTO_START, Windows::ServiceConstants::SERVICE_BOOT_START, Windows::ServiceConstants::SERVICE_CHANGE_CONFIG, Windows::ServiceConstants::SERVICE_CONFIG_DELAYED_AUTO_START_INFO, Windows::ServiceConstants::SERVICE_CONFIG_DESCRIPTION, Windows::ServiceConstants::SERVICE_CONFIG_FAILURE_ACTIONS, Windows::ServiceConstants::SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, Windows::ServiceConstants::SERVICE_CONFIG_PRESHUTDOWN_INFO, Windows::ServiceConstants::SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, Windows::ServiceConstants::SERVICE_CONFIG_SERVICE_SID_INFO, Windows::ServiceConstants::SERVICE_CONTINUE_PENDING, Windows::ServiceConstants::SERVICE_CONTROL_CONTINUE, Windows::ServiceConstants::SERVICE_CONTROL_DEVICEEVENT, Windows::ServiceConstants::SERVICE_CONTROL_HARDWAREPROFILECHANGE, Windows::ServiceConstants::SERVICE_CONTROL_INTERROGATE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDADD, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDDISABLE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDENABLE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDREMOVE, Windows::ServiceConstants::SERVICE_CONTROL_PARAMCHANGE, Windows::ServiceConstants::SERVICE_CONTROL_PAUSE, Windows::ServiceConstants::SERVICE_CONTROL_POWEREVENT, Windows::ServiceConstants::SERVICE_CONTROL_PRESHUTDOWN, Windows::ServiceConstants::SERVICE_CONTROL_SESSIONCHANGE, Windows::ServiceConstants::SERVICE_CONTROL_SHUTDOWN, Windows::ServiceConstants::SERVICE_CONTROL_STOP, Windows::ServiceConstants::SERVICE_CONTROL_TIMECHANGE, Windows::ServiceConstants::SERVICE_CONTROL_TRIGGEREVENT, Windows::ServiceConstants::SERVICE_DEMAND_START, Windows::ServiceConstants::SERVICE_DISABLED, Windows::ServiceConstants::SERVICE_DRIVER, Windows::ServiceConstants::SERVICE_ENUMERATE_DEPENDENTS, Windows::ServiceConstants::SERVICE_ERROR_CRITICAL, Windows::ServiceConstants::SERVICE_ERROR_IGNORE, Windows::ServiceConstants::SERVICE_ERROR_NORMAL, Windows::ServiceConstants::SERVICE_ERROR_SEVERE, Windows::ServiceConstants::SERVICE_FILE_SYSTEM_DRIVER, Windows::ServiceConstants::SERVICE_INACTIVE, Windows::ServiceConstants::SERVICE_INTERACTIVE_PROCESS, Windows::ServiceConstants::SERVICE_INTERROGATE, Windows::ServiceConstants::SERVICE_KERNEL_DRIVER, Windows::ServiceConstants::SERVICE_NO_CHANGE, Windows::ServiceConstants::SERVICE_PAUSED, Windows::ServiceConstants::SERVICE_PAUSE_CONTINUE, Windows::ServiceConstants::SERVICE_PAUSE_PENDING, Windows::ServiceConstants::SERVICE_QUERY_CONFIG, Windows::ServiceConstants::SERVICE_QUERY_STATUS, Windows::ServiceConstants::SERVICE_RECOGNIZER_DRIVER, Windows::ServiceConstants::SERVICE_RUNNING, Windows::ServiceConstants::SERVICE_START, Windows::ServiceConstants::SERVICE_START_PENDING, Windows::ServiceConstants::SERVICE_STATE_ALL, Windows::ServiceConstants::SERVICE_STOP, Windows::ServiceConstants::SERVICE_STOPPED, Windows::ServiceConstants::SERVICE_STOP_PENDING, Windows::ServiceConstants::SERVICE_SYSTEM_START, Windows::ServiceConstants::SERVICE_TYPE_ALL, Windows::ServiceConstants::SERVICE_USER_DEFINED_CONTROL, Windows::ServiceConstants::SERVICE_WIN32, Windows::ServiceConstants::SERVICE_WIN32_OWN_PROCESS, Windows::ServiceConstants::SERVICE_WIN32_SHARE_PROCESS, Windows::ServiceConstants::SE_PRIVILEGE_ENABLED, Windows::ServiceConstants::TOKEN_ADJUST_PRIVILEGES, Windows::ServiceConstants::TOKEN_QUERY, Windows::ServiceConstants::WAIT_FAILED, Windows::ServiceConstants::WAIT_OBJECT_0, Windows::ServiceConstants::WAIT_TIMEOUT
Class Method Summary collapse
- .close_service_handle(handle) ⇒ Object
-
.config_info(service, host = nil) ⇒ Object
Returns a ServiceConfigInfo struct containing the configuration information about
service
onhost
, or the local host if no host is specified. -
.configure(options = {}) ⇒ Object
Configures the named
service
onhost
, or the local host if no host is specified. -
.configure_failure_actions(handle_scs, opts) ⇒ Object
Configures failure actions for a given service.
-
.delayed_start(service, host = nil) ⇒ Integer, ...
Attempts to get the delayed_start attribute for the named
service
onhost
, or the local machine if no host is provided. -
.delete(service, host = nil) ⇒ Object
Deletes the specified
service
fromhost
, or the local host if no host is specified. -
.exists?(service, host = nil) ⇒ Boolean
Returns whether or not
service
exists onhost
or localhost, if no host is specified. -
.get_action_type(action_type) ⇒ Object
Returns a human readable string indicating the action type.
-
.get_config2_info(handle, info_level) ⇒ Object
Shortcut for QueryServiceConfig2.
-
.get_config_info(handle) ⇒ Object
Shortcut for QueryServiceConfig.
-
.get_controls_accepted(controls) ⇒ Object
Returns an array of human readable strings indicating the controls that the service accepts.
-
.get_current_state(state) ⇒ Object
Converts a service state numeric constant into a readable string.
-
.get_display_name(service, host = nil) ⇒ Object
(also: getdisplayname)
Returns the display name of the specified service name, i.e.
-
.get_error_control(error_control) ⇒ Object
Returns a human readable string indicating the error control.
-
.get_service_name(display_name, host = nil) ⇒ Object
(also: getservicename)
Returns the service name of the specified service from the provided
display_name
. -
.get_service_type(service_type) ⇒ Object
Converts a service type numeric constant into a human readable string.
-
.get_start_type(start_type) ⇒ Object
Returns a human readable string indicating the start type.
-
.open_sc_manager(host = nil, desired_access = SC_MANAGER_CONNECT) ⇒ Integer
Establishes a connection to the service control manager on the specified host and opens the SERVICES_ACTIVE_DATABASE service control manager database.
-
.open_service(scm_handle, service_name, desired_access) ⇒ Object
Opens an existing service.
-
.pause(service, host = nil) ⇒ Object
Pauses the given
service
onhost
, or the local host if no host is specified. -
.resume(service, host = nil) ⇒ Object
Resume the given
service
onhost
, or the local host if no host is specified. -
.send_signal(service, host, service_signal, control_signal) ⇒ Object
A shortcut method that simplifies the various service control methods.
-
.services(host = nil, group = nil) ⇒ Object
Enumerates over a list of service types on
host
, or the local machine if no host is specified, yielding a ServiceInfo struct for each service. -
.start(service, host = nil, *args) ⇒ Object
Attempts to start the named
service
onhost
, or the local machine if no host is provided. -
.status(service, host = nil) ⇒ Object
Returns a ServiceStatus struct indicating the status of service
name
onhost
, or the localhost if none is provided. -
.stop(service, host = nil) ⇒ Object
Stops a the given
service
onhost
, or the local host if no host is specified.
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Service
constructor
Creates a new service with the specified
options
.
Constructor Details
#initialize(options = {}) ⇒ Service
Creates a new service with the specified options
. A service_name
must be specified or an ArgumentError is raised. A host
option may be specified. If no host is specified the local machine is used.
Possible Options:
-
service_name => nil (you must specify)
-
host => nil (optional)
-
display_name => service_name
-
desired_access => Service::ALL_ACCESS
-
service_type => Service::WIN32_OWN_PROCESS
-
start_type => Service::DEMAND_START
-
error_control => Service::ERROR_NORMAL
-
binary_path_name => nil
-
load_order_group => nil
-
dependencies => nil
-
service_start_name => nil
-
password => nil
-
description => nil
-
failure_reset_period => nil,
-
failure_reboot_message => nil,
-
failure_command => nil,
-
failure_actions => nil,
-
failure_delay => 0
Example:
# Configure everything
Service.new(
:service_name => 'some_service',
:host => 'localhost',
:service_type => Service::WIN32_OWN_PROCESS,
:description => 'A custom service I wrote just for fun',
:start_type => Service::AUTO_START,
:error_control => Service::ERROR_NORMAL,
:binary_path_name => 'C:\path\to\some_service.exe',
:load_order_group => 'Network',
:dependencies => ['W32Time','Schedule'],
:service_start_name => 'SomeDomain\\User',
:password => 'XXXXXXX',
:display_name => 'This is some service',
)
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
# File 'lib/win32/service.rb', line 294 def initialize( = {}) unless .is_a?(Hash) raise ArgumentError, "options parameter must be a hash" end if .empty? raise ArgumentError, "no options provided" end opts = { "display_name" => nil, "desired_access" => SERVICE_ALL_ACCESS, "service_type" => SERVICE_WIN32_OWN_PROCESS, "start_type" => SERVICE_DEMAND_START, "error_control" => SERVICE_ERROR_NORMAL, "binary_path_name" => nil, "load_order_group" => nil, "dependencies" => nil, "service_start_name" => nil, "password" => nil, "description" => nil, "failure_reset_period" => nil, "failure_reboot_message" => nil, "failure_command" => nil, "failure_actions" => nil, "failure_delay" => 0, "host" => nil, "service_name" => nil, } # Validate the hash options .each { |key, value| key = key.to_s.downcase unless opts.include?(key) raise ArgumentError, "Invalid option '#{key}'" end opts[key] = value } unless opts["service_name"] raise ArgumentError, "No service_name specified" end service_name = opts.delete("service_name") host = opts.delete("host") raise TypeError unless service_name.is_a?(String) raise TypeError if host && !host.is_a?(String) begin handle_scm = OpenSCManager(host, nil, SC_MANAGER_CREATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 # Display name defaults to service_name opts["display_name"] ||= service_name dependencies = opts["dependencies"] if dependencies && !dependencies.empty? unless dependencies.is_a?(Array) || dependencies.is_a?(String) raise TypeError, "dependencies must be a string or array" end if dependencies.is_a?(Array) dependencies = dependencies.join("\000") end dependencies += "\000" dependencies = FFI::MemoryPointer.from_string(dependencies) end handle_scs = CreateService( handle_scm, service_name, opts["display_name"], opts["desired_access"], opts["service_type"], opts["start_type"], opts["error_control"], opts["binary_path_name"], opts["load_order_group"], nil, dependencies, opts["service_start_name"], opts["password"] ) FFI.raise_windows_error("CreateService") if handle_scs == 0 if opts["description"] description = SERVICE_DESCRIPTION.new description[:lpDescription] = FFI::MemoryPointer.from_string(opts["description"]) bool = ChangeServiceConfig2( handle_scs, SERVICE_CONFIG_DESCRIPTION, description ) FFI.raise_windows_error("ChangeServiceConfig2") unless bool end if opts["failure_reset_period"] || opts["failure_reboot_message"] || opts["failure_command"] || opts["failure_actions"] self.class.configure_failure_actions(handle_scs, opts) end ensure self.class.close_service_handle(handle_scs) self.class.close_service_handle(handle_scm) end self end |
Class Method Details
.close_service_handle(handle) ⇒ Object
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 |
# File 'lib/win32/service.rb', line 1226 def self.close_service_handle(handle) case handle when NilClass false when Integer handle > 0 ? CloseServiceHandle(handle) : false else raise ArgumentError, "You must pass a valid handle to ::close_service_handle" end end |
.config_info(service, host = nil) ⇒ Object
Returns a ServiceConfigInfo struct containing the configuration information about service
on host
, or the local host if no host is specified.
Example:
Service.config_info('W32Time') => <struct ServiceConfigInfo ...>
– This contains less information that the ServiceInfo struct that is returned with the Service.services method, but is faster for looking up basic information for a single service.
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 |
# File 'lib/win32/service.rb', line 848 def self.config_info(service, host = nil) raise TypeError if host && !host.is_a?(String) handle_scm = OpenSCManager(host, nil, SC_MANAGER_ENUMERATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 begin handle_scs = OpenService(handle_scm, service, SERVICE_QUERY_CONFIG) FFI.raise_windows_error("OpenService") if handle_scs == 0 # First, get the buf size needed bytes = FFI::MemoryPointer.new(:ulong) bool = QueryServiceConfig(handle_scs, nil, 0, bytes) if !bool && FFI.errno != ERROR_INSUFFICIENT_BUFFER FFI.raise_windows_error("QueryServiceConfig") end buf = FFI::MemoryPointer.new(:char, bytes.read_ulong) bytes = FFI::MemoryPointer.new(:ulong) bool = QueryServiceConfig(handle_scs, buf, buf.size, bytes) struct = QUERY_SERVICE_CONFIG.new(buf) # cast the buffer FFI.raise_windows_error("QueryServiceConfig") unless bool ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end ConfigStruct.new( get_service_type(struct[:dwServiceType]), get_start_type(struct[:dwStartType]), get_error_control(struct[:dwErrorControl]), struct[:lpBinaryPathName].read_string, struct[:lpLoadOrderGroup].read_string, struct[:dwTagId], struct.dependencies, struct[:lpServiceStartName].read_string, struct[:lpDisplayName].read_string ) end |
.configure(options = {}) ⇒ Object
Configures the named service
on host
, or the local host if no host is specified. The options
parameter is a hash that can contain any of the following parameters:
-
service_type
-
start_type
-
error_control
-
binary_path_name
-
load_order_group
-
dependencies
-
service_start_name
-
password (used with service_start_name)
-
display_name
-
description
-
failure_reset_period
-
failure_reboot_message
-
failure_command
-
failure_actions
-
failure_delay
Examples:
# Configure only the display name
Service.configure(
:service_name => 'some_service',
:display_name => 'Test 33'
)
# Configure everything
Service.configure(
:service_name => 'some_service'
:service_type => Service::WIN32_OWN_PROCESS,
:start_type => Service::AUTO_START,
:error_control => Service::ERROR_NORMAL,
:binary_path_name => 'C:\path\to\some_service.exe',
:load_order_group => 'Network',
:dependencies => ['W32Time','Schedule']
:service_start_name => 'SomeDomain\\User',
:password => 'XXXXXXX',
:display_name => 'This is some service',
:description => 'A custom service I wrote just for fun'
)
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
# File 'lib/win32/service.rb', line 453 def self.configure( = {}) unless .is_a?(Hash) raise ArgumentError, "options parameter must be a hash" end if .empty? raise ArgumentError, "no options provided" end opts = { "service_type" => SERVICE_NO_CHANGE, "start_type" => SERVICE_NO_CHANGE, "error_control" => SERVICE_NO_CHANGE, "binary_path_name" => nil, "load_order_group" => nil, "dependencies" => nil, "service_start_name" => nil, "password" => nil, "display_name" => nil, "description" => nil, "failure_reset_period" => nil, "failure_reboot_message" => nil, "failure_command" => nil, "failure_actions" => nil, "failure_delay" => 0, "service_name" => nil, "host" => nil, "delayed_start" => false, } # Validate the hash options .each { |key, value| key = key.to_s.downcase unless opts.include?(key) raise ArgumentError, "Invalid option '#{key}'" end opts[key] = value } unless opts["service_name"] raise ArgumentError, "No service_name specified" end service = opts.delete("service_name") host = opts.delete("host") raise TypeError unless service.is_a?(String) if host raise TypeError unless host.is_a?(String) end begin handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 desired_access = SERVICE_CHANGE_CONFIG if opts["failure_actions"] desired_access |= SERVICE_START end handle_scs = OpenService( handle_scm, service, desired_access ) FFI.raise_windows_error("OpenService") if handle_scs == 0 dependencies = opts["dependencies"] if dependencies && !dependencies.empty? unless dependencies.is_a?(Array) || dependencies.is_a?(String) raise TypeError, "dependencies must be a string or array" end if dependencies.is_a?(Array) dependencies = dependencies.join("\000") end dependencies += "\000" end bool = ChangeServiceConfig( handle_scs, opts["service_type"], opts["start_type"], opts["error_control"], opts["binary_path_name"], opts["load_order_group"], nil, dependencies, opts["service_start_name"], opts["password"], opts["display_name"] ) FFI.raise_windows_error("ChangeServiceConfig") unless bool if opts["description"] description = SERVICE_DESCRIPTION.new description[:lpDescription] = FFI::MemoryPointer.from_string(opts["description"]) bool = ChangeServiceConfig2( handle_scs, SERVICE_CONFIG_DESCRIPTION, description ) FFI.raise_windows_error("ChangeServiceConfig2") unless bool end if opts["delayed_start"] delayed_start = SERVICE_DELAYED_AUTO_START_INFO.new delayed_start[:fDelayedAutostart] = opts["delayed_start"] bool = ChangeServiceConfig2( handle_scs, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayed_start ) FFI.raise_windows_error("ChangeServiceConfig2") unless bool end if opts["failure_reset_period"] || opts["failure_reboot_message"] || opts["failure_command"] || opts["failure_actions"] configure_failure_actions(handle_scs, opts) end ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end self end |
.configure_failure_actions(handle_scs, opts) ⇒ Object
Configures failure actions for a given service.
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
# File 'lib/win32/service.rb', line 1306 def self.configure_failure_actions(handle_scs, opts) if opts["failure_actions"] token_handle = FFI::MemoryPointer.new(:ulong) bool = OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, token_handle ) unless bool error = FFI.errno close_service_handle(handle_scs) raise SystemCallError.new("OpenProcessToken", error) end token_handle = token_handle.read_ulong # Get the LUID for shutdown privilege. luid = LUID.new unless LookupPrivilegeValue("", "SeShutdownPrivilege", luid) error = FFI.errno close_service_handle(handle_scs) raise SystemCallError.new("LookupPrivilegeValue", error) end luid_and_attrs = LUID_AND_ATTRIBUTES.new luid_and_attrs[:Luid] = luid luid_and_attrs[:Attributes] = SE_PRIVILEGE_ENABLED tkp = TOKEN_PRIVILEGES.new tkp[:PrivilegeCount] = 1 tkp[:Privileges][0] = luid_and_attrs # Enable shutdown privilege in access token of this process bool = AdjustTokenPrivileges( token_handle, 0, tkp, tkp.size, nil, nil ) unless bool error = FFI.errno close_service_handle(handle_scs) raise SystemCallError.new("AdjustTokenPrivileges", error) end end sfa = SERVICE_FAILURE_ACTIONS.new if opts["failure_reset_period"] sfa[:dwResetPeriod] = opts["failure_reset_period"] end if opts["failure_reboot_message"] sfa[:lpRebootMsg] = FFI::MemoryPointer.from_string(opts["failure_reboot_message"]) end if opts["failure_command"] sfa[:lpCommand] = FFI::MemoryPointer.from_string(opts["failure_command"]) end if opts["failure_actions"] action_size = opts["failure_actions"].size action_ptr = FFI::MemoryPointer.new(SC_ACTION, action_size) actions = action_size.times.collect do |i| SC_ACTION.new(action_ptr + i * SC_ACTION.size) end opts["failure_actions"].each_with_index { |action, i| actions[i][:Type] = action actions[i][:Delay] = opts["failure_delay"] } sfa[:cActions] = action_size sfa[:lpsaActions] = action_ptr end bool = ChangeServiceConfig2( handle_scs, SERVICE_CONFIG_FAILURE_ACTIONS, sfa ) unless bool error = FFI.errno close_service_handle(handle_scs) raise SystemCallError.new("ChangeServiceConfig2", error) end end |
.delayed_start(service, host = nil) ⇒ Integer, ...
Attempts to get the delayed_start attribute for the named service
on host
, or the local machine if no host is provided.
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 |
# File 'lib/win32/service.rb', line 1199 def self.delayed_start(service, host = nil) handle_scm = OpenSCManager(host, nil, SC_MANAGER_ENUMERATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 handle_scs = OpenService( handle_scm, service, SERVICE_QUERY_CONFIG ) FFI.raise_windows_error("OpenService") if handle_scs == 0 delayed_start_buf = get_config2_info(handle_scs, SERVICE_CONFIG_DELAYED_AUTO_START_INFO) if delayed_start_buf.is_a?(FFI::MemoryPointer) delayed_start_info = SERVICE_DELAYED_AUTO_START_INFO.new(delayed_start_buf) delayed_start = delayed_start_info[:fDelayedAutostart] else delayed_start = false end rescue SystemCallError delayed_start = nil ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end |
.delete(service, host = nil) ⇒ Object
Deletes the specified service
from host
, or the local host if no host is specified. Returns self.
Technical note. This method is not instantaneous. The service is first marked for deletion from the service control manager database. Then all handles to the service are closed. Then an attempt to stop the service is made. If the service cannot be stopped, the service control manager database entry is removed when the system is restarted.
Example:
Service.delete('SomeService') => self
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
# File 'lib/win32/service.rb', line 815 def self.delete(service, host = nil) handle_scm = OpenSCManager(host, nil, SC_MANAGER_CREATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 begin handle_scs = OpenService(handle_scm, service, DELETE) FFI.raise_windows_error("OpenService") if handle_scs == 0 unless DeleteService(handle_scs) FFI.raise_windows_error("DeleteService") end ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end self end |
.exists?(service, host = nil) ⇒ Boolean
Returns whether or not service
exists on host
or localhost, if no host is specified.
Example:
Service.exists?(‘W32Time’) => true
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 |
# File 'lib/win32/service.rb', line 600 def self.exists?(service, host = nil) bool = false begin handle_scm = OpenSCManager(host, nil, SC_MANAGER_ENUMERATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 handle_scs = OpenService(handle_scm, service, SERVICE_QUERY_STATUS) bool = true if handle_scs > 0 ensure close_service_handle(handle_scm) close_service_handle(handle_scs) end bool end |
.get_action_type(action_type) ⇒ Object
Returns a human readable string indicating the action type.
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 |
# File 'lib/win32/service.rb', line 1404 def self.get_action_type(action_type) case action_type when SC_ACTION_NONE "none" when SC_ACTION_REBOOT "reboot" when SC_ACTION_RESTART "restart" when SC_ACTION_RUN_COMMAND "command" else "unknown" end end |
.get_config2_info(handle, info_level) ⇒ Object
Shortcut for QueryServiceConfig2. Returns the buffer.
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 |
# File 'lib/win32/service.rb', line 1461 def self.get_config2_info(handle, info_level) bytes_needed = FFI::MemoryPointer.new(:ulong) # First attempt at QueryServiceConfig2 is to get size needed bool = QueryServiceConfig2(handle, info_level, nil, 0, bytes_needed) err_num = FFI.errno # This is a bit hacky since it means we have to check the type of value # we get back, but we don't always want to raise an error either, # depending on what we're trying to get at. # if !bool && err_num == ERROR_INSUFFICIENT_BUFFER config2_buf = FFI::MemoryPointer.new(:char, bytes_needed.read_ulong) elsif [ERROR_FILE_NOT_FOUND, ERROR_RESOURCE_TYPE_NOT_FOUND, ERROR_RESOURCE_NAME_NOT_FOUND].include?(err_num) return err_num else CloseServiceHandle(handle) FFI.raise_windows_error("QueryServiceConfig2", err_num) end bytes_needed.clear # Second attempt at QueryServiceConfig2 gets the actual info begin bool = QueryServiceConfig2( handle, info_level, config2_buf, config2_buf.size, bytes_needed ) FFI.raise_windows_error("QueryServiceConfig2") unless bool ensure CloseServiceHandle(handle) unless bool end config2_buf end |
.get_config_info(handle) ⇒ Object
Shortcut for QueryServiceConfig. Returns the buffer. In rare cases the underlying registry entry may have been deleted, but the service still exists. In that case, the ERROR_FILE_NOT_FOUND value is returned instead.
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 |
# File 'lib/win32/service.rb', line 1424 def self.get_config_info(handle) bytes_needed = FFI::MemoryPointer.new(:ulong) # First attempt at QueryServiceConfig is to get size needed bool = QueryServiceConfig(handle, nil, 0, bytes_needed) if !bool && FFI.errno == ERROR_INSUFFICIENT_BUFFER config_buf = FFI::MemoryPointer.new(:char, bytes_needed.read_ulong) elsif FFI.errno == ERROR_FILE_NOT_FOUND return FFI.errno else error = FFI.errno CloseServiceHandle(handle) FFI.raise_windows_error("QueryServiceConfig", error) end bytes_needed.clear # Second attempt at QueryServiceConfig gets the actual info begin bool = QueryServiceConfig( handle, config_buf, config_buf.size, bytes_needed ) FFI.raise_windows_error("QueryServiceConfig") unless bool ensure CloseServiceHandle(handle) unless bool end QUERY_SERVICE_CONFIG.new(config_buf) # cast the buffer end |
.get_controls_accepted(controls) ⇒ Object
Returns an array of human readable strings indicating the controls that the service accepts.
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 |
# File 'lib/win32/service.rb', line 1541 def self.get_controls_accepted(controls) array = [] if controls & SERVICE_ACCEPT_NETBINDCHANGE > 0 array << "netbind change" end if controls & SERVICE_ACCEPT_PARAMCHANGE > 0 array << "param change" end if controls & SERVICE_ACCEPT_PAUSE_CONTINUE > 0 array << "pause continue" end if controls & SERVICE_ACCEPT_SHUTDOWN > 0 array << "shutdown" end if controls & SERVICE_ACCEPT_PRESHUTDOWN > 0 array << "pre-shutdown" end if controls & SERVICE_ACCEPT_STOP > 0 array << "stop" end if controls & SERVICE_ACCEPT_HARDWAREPROFILECHANGE > 0 array << "hardware profile change" end if controls & SERVICE_ACCEPT_POWEREVENT > 0 array << "power event" end if controls & SERVICE_ACCEPT_SESSIONCHANGE > 0 array << "session change" end array end |
.get_current_state(state) ⇒ Object
Converts a service state numeric constant into a readable string.
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 |
# File 'lib/win32/service.rb', line 1585 def self.get_current_state(state) case state when SERVICE_CONTINUE_PENDING "continue pending" when SERVICE_PAUSE_PENDING "pause pending" when SERVICE_PAUSED "paused" when SERVICE_RUNNING "running" when SERVICE_START_PENDING "start pending" when SERVICE_STOP_PENDING "stop pending" when SERVICE_STOPPED "stopped" else nil end end |
.get_display_name(service, host = nil) ⇒ Object Also known as: getdisplayname
Returns the display name of the specified service name, i.e. the string displayed in the Services GUI. Raises a Service::Error if the service name cannot be found.
If a host
is provided, the information will be retrieved from that host. Otherwise, the information is pulled from the local host (the default behavior).
Example:
Service.get_display_name(‘W32Time’) => ‘Windows Time’
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/win32/service.rb', line 630 def self.get_display_name(service, host = nil) handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 display_name = FFI::MemoryPointer.new(260) display_size = FFI::MemoryPointer.new(:ulong) display_size.write_ulong(display_name.size) begin bool = GetServiceDisplayName( handle_scm, service, display_name, display_size ) FFI.raise_windows_error("OpenSCManager") unless bool ensure close_service_handle(handle_scm) end display_name.read_string end |
.get_error_control(error_control) ⇒ Object
Returns a human readable string indicating the error control
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 |
# File 'lib/win32/service.rb', line 1504 def self.get_error_control(error_control) case error_control when SERVICE_ERROR_CRITICAL "critical" when SERVICE_ERROR_IGNORE "ignore" when SERVICE_ERROR_NORMAL "normal" when SERVICE_ERROR_SEVERE "severe" else nil end end |
.get_service_name(display_name, host = nil) ⇒ Object Also known as: getservicename
Returns the service name of the specified service from the provided display_name
. Raises a Service::Error if the display_name
cannote be found.
If a host
is provided, the information will be retrieved from that host. Otherwise, the information is pulled from the local host (the default behavior).
Example:
Service.get_service_name(‘Windows Time’) => ‘W32Time’
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 |
# File 'lib/win32/service.rb', line 667 def self.get_service_name(display_name, host = nil) handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 service_name = FFI::MemoryPointer.new(260) service_size = FFI::MemoryPointer.new(:ulong) service_size.write_ulong(service_name.size) begin bool = GetServiceKeyName( handle_scm, display_name, service_name, service_size ) FFI.raise_windows_error("GetServiceKeyName") unless bool ensure close_service_handle(handle_scm) end service_name.read_string end |
.get_service_type(service_type) ⇒ Object
Converts a service type numeric constant into a human readable string.
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 |
# File 'lib/win32/service.rb', line 1608 def self.get_service_type(service_type) case service_type when SERVICE_FILE_SYSTEM_DRIVER "file system driver" when SERVICE_KERNEL_DRIVER "kernel driver" when SERVICE_WIN32_OWN_PROCESS "own process" when SERVICE_WIN32_SHARE_PROCESS "share process" when SERVICE_RECOGNIZER_DRIVER "recognizer driver" when SERVICE_DRIVER "driver" when SERVICE_WIN32 "win32" when SERVICE_TYPE_ALL "all" when SERVICE_INTERACTIVE_PROCESS | SERVICE_WIN32_OWN_PROCESS "own process, interactive" when SERVICE_INTERACTIVE_PROCESS | SERVICE_WIN32_SHARE_PROCESS "share process, interactive" else nil end end |
.get_start_type(start_type) ⇒ Object
Returns a human readable string indicating the start type.
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 |
# File 'lib/win32/service.rb', line 1521 def self.get_start_type(start_type) case start_type when SERVICE_AUTO_START "auto start" when SERVICE_BOOT_START "boot start" when SERVICE_DEMAND_START "demand start" when SERVICE_DISABLED "disabled" when SERVICE_SYSTEM_START "system start" else nil end end |
.open_sc_manager(host = nil, desired_access = SC_MANAGER_CONNECT) ⇒ Integer
Establishes a connection to the service control manager on the specified host and opens the SERVICES_ACTIVE_DATABASE service control manager database.
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 |
# File 'lib/win32/service.rb', line 1291 def self.open_sc_manager(host = nil, desired_access = SC_MANAGER_CONNECT) scm_handle = OpenSCManager(host, nil, desired_access) FFI.raise_windows_error("OpenSCManager") if scm_handle == 0 if block_given? yield scm_handle else scm_handle end ensure close_service_handle(scm_handle) if block_given? end |
.open_service(scm_handle, service_name, desired_access) ⇒ Object
Opens an existing service.
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 |
# File 'lib/win32/service.rb', line 1254 def self.open_service(scm_handle, service_name, desired_access) service_handle = OpenService( scm_handle, service_name, desired_access ) FFI.raise_windows_error("OpenService") if service_handle == 0 if block_given? yield service_handle else service_handle end ensure close_service_handle(service_handle) if block_given? end |
.pause(service, host = nil) ⇒ Object
Pauses the given service
on host
, or the local host if no host is specified. Returns self
Note that pausing a service that is already paused will have no effect and it will not raise an error.
Be aware that not all services are configured to accept a pause command. Attempting to pause a service that isn’t setup to receive a pause command will raise an error.
Example:
Service.pause('Schedule') => self
778 779 780 781 782 783 |
# File 'lib/win32/service.rb', line 778 def self.pause(service, host = nil) service_signal = SERVICE_PAUSE_CONTINUE control_signal = SERVICE_CONTROL_PAUSE send_signal(service, host, service_signal, control_signal) self end |
.resume(service, host = nil) ⇒ Object
Resume the given service
on host
, or the local host if no host is specified. Returns self.
Note that resuming a service that’s already running will have no effect and it will not raise an error.
Example:
Service.resume('Schedule') => self
795 796 797 798 799 800 |
# File 'lib/win32/service.rb', line 795 def self.resume(service, host = nil) service_signal = SERVICE_PAUSE_CONTINUE control_signal = SERVICE_CONTROL_CONTINUE send_signal(service, host, service_signal, control_signal) self end |
.send_signal(service, host, service_signal, control_signal) ⇒ Object
A shortcut method that simplifies the various service control methods.
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 |
# File 'lib/win32/service.rb', line 1637 def self.send_signal(service, host, service_signal, control_signal) handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 begin handle_scs = OpenService(handle_scm, service, service_signal) FFI.raise_windows_error("OpenService") if handle_scs == 0 status = SERVICE_STATUS.new unless ControlService(handle_scs, control_signal, status) FFI.raise_windows_error("ControlService") end ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end status end |
.services(host = nil, group = nil) ⇒ Object
Enumerates over a list of service types on host
, or the local machine if no host is specified, yielding a ServiceInfo struct for each service.
If a group
is specified, then only those services that belong to that load order group are enumerated. If an empty string is provided, then only services that do not belong to any group are enumerated. If this parameter is nil (the default), group membership is ignored and all services are enumerated. This value is not case sensitive.
Examples:
# Enumerate over all services on the localhost
Service.services{ |service| p service }
# Enumerate over all services on a remote host
Service.services('some_host'){ |service| p service }
# Enumerate over all 'network' services locally
Service.services(nil, 'network'){ |service| p service }
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 |
# File 'lib/win32/service.rb', line 962 def self.services(host = nil, group = nil) unless host.nil? raise TypeError unless host.is_a?(String) # Avoid strange errors end unless group.nil? raise TypeError unless group.is_a?(String) # Avoid strange errors end handle_scm = OpenSCManager(host, nil, SC_MANAGER_ENUMERATE_SERVICE) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 bytes_needed = FFI::MemoryPointer.new(:ulong) services_returned = FFI::MemoryPointer.new(:ulong) resume_handle = FFI::MemoryPointer.new(:ulong) begin # The first call is used to determine the required buffer size bool = EnumServicesStatusEx( handle_scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32 | SERVICE_DRIVER, SERVICE_STATE_ALL, nil, 0, bytes_needed, services_returned, resume_handle, group ) if !bool && FFI.errno == ERROR_MORE_DATA service_buf = FFI::MemoryPointer.new(:char, bytes_needed.read_ulong) else FFI.raise_windows_error("EnumServiceStatusEx") end bool = EnumServicesStatusEx( handle_scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32 | SERVICE_DRIVER, SERVICE_STATE_ALL, service_buf, service_buf.size, bytes_needed, services_returned, resume_handle, group ) FFI.raise_windows_error("EnumServiceStatusEx") unless bool num_services = services_returned.read_ulong services_array = [] unless block_given? 1.upto(num_services) { |num| # Cast the buffer struct = ENUM_SERVICE_STATUS_PROCESS.new(service_buf) service_name = struct[:lpServiceName].read_string display_name = struct[:lpDisplayName].read_string service_type = get_service_type(struct[:ServiceStatusProcess][:dwServiceType]) current_state = get_current_state(struct[:ServiceStatusProcess][:dwCurrentState]) controls = get_controls_accepted(struct[:ServiceStatusProcess][:dwControlsAccepted]) interactive = struct[:ServiceStatusProcess][:dwServiceType] & SERVICE_INTERACTIVE_PROCESS > 0 win_exit_code = struct[:ServiceStatusProcess][:dwWin32ExitCode] ser_exit_code = struct[:ServiceStatusProcess][:dwServiceSpecificExitCode] check_point = struct[:ServiceStatusProcess][:dwCheckPoint] wait_hint = struct[:ServiceStatusProcess][:dwWaitHint] pid = struct[:ServiceStatusProcess][:dwProcessId] service_flags = struct[:ServiceStatusProcess][:dwServiceFlags] begin handle_scs = OpenService( handle_scm, service_name, SERVICE_QUERY_CONFIG ) FFI.raise_windows_error("OpenService") if handle_scs == 0 config_struct = get_config_info(handle_scs) if config_struct != ERROR_FILE_NOT_FOUND binary_path = config_struct[:lpBinaryPathName].read_string load_order = config_struct[:lpLoadOrderGroup].read_string start_name = config_struct[:lpServiceStartName].read_string tag_id = config_struct[:dwTagId] start_type = get_start_type(config_struct[:dwStartType]) error_ctrl = get_error_control(config_struct[:dwErrorControl]) deps = config_struct.dependencies begin buf = get_config2_info(handle_scs, SERVICE_CONFIG_DESCRIPTION) if buf.is_a?(Numeric) || buf.read_pointer.null? description = "" else description = buf.read_pointer.read_string end rescue # While being annoying, not being able to get a description is not exceptional warn "WARNING: Failed to retrieve description for the #{service_name} service." description = "" end delayed_start = delayed_start(service_name) else warn "WARNING: The registry entry for the #{service_name} service could not be found" binary_path = nil load_order = nil start_name = nil start_type = nil error_ctrl = nil tag_id = nil deps = nil description = nil end begin buf2 = get_config2_info(handle_scs, SERVICE_CONFIG_FAILURE_ACTIONS) if buf2.is_a?(FFI::MemoryPointer) fail_struct = SERVICE_FAILURE_ACTIONS.new(buf2) reset_period = fail_struct[:dwResetPeriod] num_actions = fail_struct[:cActions] if fail_struct[:lpRebootMsg].null? reboot_msg = nil else reboot_msg = fail_struct[:lpRebootMsg].read_string end if fail_struct[:lpCommand].null? command = nil else command = fail_struct[:lpCommand].read_string end actions = nil if num_actions > 0 action_ptr = fail_struct[:lpsaActions] actions = {} num_actions.times { |n| sc_action = SC_ACTION.new(action_ptr[n * SC_ACTION.size]) delay = sc_action[:Delay] action_type = get_action_type(sc_action[:Type]) actions[n + 1] = { action_type: action_type, delay: delay } } end else reset_period = nil reboot_msg = nil command = nil actions = nil end rescue warn "WARNING: Unable to retrieve failure actions for the #{service_name} service" reset_period = nil reboot_msg = nil command = nil actions = nil end ensure close_service_handle(handle_scs) end struct = ServiceStruct.new( service_name, display_name, service_type, current_state, controls, win_exit_code, ser_exit_code, check_point, wait_hint, binary_path, start_type, error_ctrl, load_order, tag_id, start_name, deps, description, interactive, pid, service_flags, reset_period, reboot_msg, command, num_actions, actions, delayed_start ) if block_given? yield struct else services_array << struct end service_buf += ENUM_SERVICE_STATUS_PROCESS.size } ensure close_service_handle(handle_scm) end block_given? ? nil : services_array end |
.start(service, host = nil, *args) ⇒ Object
Attempts to start the named service
on host
, or the local machine if no host is provided. If args
are provided, they are passed to the Daemon#service_main method.
Examples:
# Start 'SomeSvc' on the local machine
Service.start('SomeSvc', nil) => self
# Start 'SomeSvc' on host 'foo', passing 'hello' as an argument
Service.start('SomeSvc', 'foo', 'hello') => self
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
# File 'lib/win32/service.rb', line 704 def self.start(service, host = nil, *args) handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT) FFI.raise_windows_error("OpenSCManager") if handle_scm == 0 begin handle_scs = OpenService(handle_scm, service, SERVICE_START) FFI.raise_windows_error("OpenService") if handle_scs == 0 num_args = 0 if args.empty? args = nil else str_ptrs = [] num_args = args.size args.each { |string| str_ptrs << FFI::MemoryPointer.from_string(string) } str_ptrs << nil vector = FFI::MemoryPointer.new(:pointer, str_ptrs.size) str_ptrs.each_with_index { |p, i| vector[i].put_pointer(0, p) } end unless StartService(handle_scs, num_args, vector) FFI.raise_windows_error("StartService") end ensure close_service_handle(handle_scs) close_service_handle(handle_scm) end self end |
.status(service, host = nil) ⇒ Object
Returns a ServiceStatus struct indicating the status of service name
on host
, or the localhost if none is provided.
Example:
Service.status(‘W32Time’) => <struct Struct::ServiceStatus …>
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 |
# File 'lib/win32/service.rb', line 902 def self.status(service, host = nil) status = SERVICE_STATUS_PROCESS.new bytes = FFI::MemoryPointer.new(:ulong) open_sc_manager(host) do |scm_handle| open_service(scm_handle, service, SERVICE_QUERY_STATUS) do |service_handle| bool = QueryServiceStatusEx( service_handle, SC_STATUS_PROCESS_INFO, status, status.size, bytes ) FFI.raise_windows_error("QueryServiceStatusEx") unless bool end end service_type = get_service_type(status[:dwServiceType]) current_state = get_current_state(status[:dwCurrentState]) controls = get_controls_accepted(status[:dwControlsAccepted]) interactive = status[:dwServiceType] & SERVICE_INTERACTIVE_PROCESS > 0 status_struct = StatusStruct.new( service_type, current_state, controls, status[:dwWin32ExitCode], status[:dwServiceSpecificExitCode], status[:dwCheckPoint], status[:dwWaitHint], interactive, status[:dwProcessId], status[:dwServiceFlags] ) status_struct end |
.stop(service, host = nil) ⇒ Object
Stops a the given service
on host
, or the local host if no host is specified. Returns self.
Note that attempting to stop an already stopped service raises Service::Error.
Example:
Service.stop('W32Time') => self
757 758 759 760 761 762 |
# File 'lib/win32/service.rb', line 757 def self.stop(service, host = nil) service_signal = SERVICE_STOP control_signal = SERVICE_CONTROL_STOP send_signal(service, host, service_signal, control_signal) self end |