def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0,
                        serviceDeps = None, userName = None, password = None,
                        exeName = None, displayName = None, perfMonIni = None, perfMonDll = None,
                        exeArgs = None, description = None, delayedstart = None):
    # Before doing anything, remove any perfmon counters.
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    # The EXE location may have changed
    exeName = '"%s"' % LocatePythonServiceExe(exeName)

    # Handle the default arguments.
    if startType is None: startType = win32service.SERVICE_NO_CHANGE
    if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    commandLine = _GetCommandLine(exeName, exeArgs)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:

            win32service.ChangeServiceConfig(hs,
                serviceType,  # service type
                startType,
                errorControl,       # error control type
                commandLine,
                None,
                0,
                serviceDeps,
                userName,
                password,
                displayName)
            if description is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
                except NotImplementedError:
                    pass    ## ChangeServiceConfig2 and description do not exist on NT
            if delayedstart is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart)
                except (win32service.error, NotImplementedError):
                    ## Delayed start only exists on Vista and later.  On Nt, will raise NotImplementedError since ChangeServiceConfig2
                    ## doensn't exist.  On Win2k and XP, will fail with ERROR_INVALID_LEVEL
                    ## Warn only if trying to set delayed to True
                    if delayedstart:
                        warnings.warn('Delayed Start not available on this system')
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
Ejemplo n.º 2
0
def _CreateService(service_name: str, description: str,
                   command_line: str) -> None:
    """Creates a Windows service."""
    logging.info("Creating service '%s'.", service_name)

    with contextlib.ExitStack() as stack:
        hscm = win32service.OpenSCManager(None, None,
                                          win32service.SC_MANAGER_ALL_ACCESS)
        stack.callback(win32service.CloseServiceHandle, hscm)
        hs = win32service.CreateService(
            hscm, service_name, service_name, win32service.SERVICE_ALL_ACCESS,
            win32service.SERVICE_WIN32_OWN_PROCESS,
            win32service.SERVICE_AUTO_START, win32service.SERVICE_ERROR_NORMAL,
            command_line, None, 0, None, None, None)
        stack.callback(win32service.CloseServiceHandle, hs)
        service_failure_actions = {
            "ResetPeriod":
            SERVICE_RESET_FAIL_COUNT_DELAY_SEC,
            "RebootMsg":
            u"",
            "Command":
            u"",
            "Actions": [
                (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC),
                (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC),
                (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC),
            ]
        }
        win32service.ChangeServiceConfig2(
            hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS,
            service_failure_actions)
        win32service.ChangeServiceConfig2(
            hs, win32service.SERVICE_CONFIG_DESCRIPTION, description)
    logging.info("Successfully created service '%s'.", service_name)
Ejemplo n.º 3
0
def setupRecoverService():
    svc_name = UDSActorSvc._svc_name_  # pylint: disable=protected-access

    try:
        hscm = win32service.OpenSCManager(None, None,
                                          win32service.SC_MANAGER_ALL_ACCESS)

        try:
            hs = win32serviceutil.SmartOpenService(
                hscm, svc_name, win32service.SERVICE_ALL_ACCESS)
            service_failure_actions = {
                'ResetPeriod':
                864000,  # Time in ms after which to reset the failure count to zero.
                'RebootMsg':
                u'',  # Not using reboot option
                'Command':
                u'',  # Not using run-command option
                'Actions': [
                    (win32service.SC_ACTION_RESTART,
                     5000),  # action, delay in ms
                    (win32service.SC_ACTION_RESTART, 5000)
                ]
            }
            win32service.ChangeServiceConfig2(
                hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS,
                service_failure_actions)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Ejemplo n.º 4
0
    def action_configure(self):
        hSCM = safe_open_scmanager()

        try:
            hSvc = safe_open_service(hSCM, self.resource.service_name)

            self._fix_start_type()

            try:
                win32service.ChangeServiceConfig(
                    hSvc, win32service.SERVICE_NO_CHANGE,
                    self.resource.start_type, win32service.SERVICE_NO_CHANGE,
                    None, None, 0, None, None, None,
                    self.resource.display_name)
                if self.resource.description:
                    try:
                        win32service.ChangeServiceConfig2(
                            hSvc, win32service.SERVICE_CONFIG_DESCRIPTION,
                            self.resource.description)
                    except NotImplementedError:
                        pass  ## ChangeServiceConfig2 and description do not exist on NT
            except win32api.error, details:
                raise Fail("Error configuring service {0}: {1}".format(
                    self.resource.service_name, details.winerror))
            finally:
                win32service.CloseServiceHandle(hSvc)
Ejemplo n.º 5
0
    def action_install(self):
        hSCM = safe_open_scmanager()

        self._fix_start_type()
        self._fix_user_name()

        try:
            hSvc = win32service.CreateService(
                hSCM,
                self.resource.service_name,
                self.resource.display_name,
                win32service.SERVICE_ALL_ACCESS,  # desired access
                win32service.SERVICE_WIN32_OWN_PROCESS,  # service type
                self.resource.start_type,
                win32service.SERVICE_ERROR_NORMAL,  # error control type
                self.resource.exe_path,
                None,
                0,
                None,
                self.resource.userName,
                self.resource.password)
            if self.resource.description:
                try:
                    win32service.ChangeServiceConfig2(
                        hSvc, win32service.SERVICE_CONFIG_DESCRIPTION,
                        self.description)
                except NotImplementedError:
                    pass  ## ChangeServiceConfig2 and description do not exist on NT

            win32service.CloseServiceHandle(hSvc)
        except win32api.error, details:
            raise Fail("Error creating service {0}: {1}".format(
                self.resource.service_name, details.winerror))
def InstallService(pythonClassString, serviceName, displayName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, perfMonIni = None, perfMonDll = None, exeArgs = None,
                   description = None, delayedstart = None):
    # Handle the default arguments.
    if startType is None:
        startType = win32service.SERVICE_DEMAND_START
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    if errorControl is None:
        errorControl = win32service.SERVICE_ERROR_NORMAL

    exeName = '"%s"' % LocatePythonServiceExe(exeName) # None here means use default PythonService.exe
    commandLine = _GetCommandLine(exeName, exeArgs)
    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:
        hs = win32service.CreateService(hscm,
                                serviceName,
                                displayName,
                                win32service.SERVICE_ALL_ACCESS,         # desired access
                    serviceType,        # service type
                    startType,
                    errorControl,       # error control type
                    commandLine,
                    None,
                    0,
                    serviceDeps,
                    userName,
                    password)
        if description is not None:
            try:
                win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
            except NotImplementedError:
                pass    ## ChangeServiceConfig2 and description do not exist on NT
        if delayedstart is not None:
            try:
                win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart)
            except (win32service.error, NotImplementedError):
                ## delayed start only exists on Vista and later - warn only when trying to set delayed to True
                if delayedstart:
                    warnings.warn('Delayed Start not available on this system')
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
 def __SetConfigrations(serviceHandle, configurationName, value):
     if value is None:
         return
     try:
         win32service.ChangeServiceConfig2(serviceHandle, configurationName, value.Win32Value())
     except NotImplementedError:
         # ChangeServiceConfig2 and/or config type not implemented on this version of NT or win32service
         pass
Ejemplo n.º 8
0
def InstallService(serviceName,
                   displayName,
                   startType=win32service.SERVICE_DEMAND_START,
                   serviceDeps=None,
                   errorControl=win32service.SERVICE_ERROR_NORMAL,
                   userName=None,
                   password=None,
                   description=None):
    """
    This is a copy of a more advanced usecase.
    For chalmers serviceName and displayName are required and the
    defaults should be sufficient
    """
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS

    script = abspath(service_script.__file__)

    if script.endswith('.pyc') or script.endswith('.pyo'):
        script = script[:-1]

    commandLine = "%s %s" % (sys.executable, script)

    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)

    try:
        hs = win32service.CreateService(
            hscm,
            serviceName,
            displayName,
            win32service.SERVICE_ALL_ACCESS,  # desired access
            serviceType,  # service type
            startType,
            errorControl,  # error control type
            commandLine,
            None,
            0,
            serviceDeps,
            userName,
            password)

        if description is not None:
            try:
                win32service.ChangeServiceConfig2(
                    hs, win32service.SERVICE_CONFIG_DESCRIPTION, description)
            except NotImplementedError:
                pass  # # ChangeServiceConfig2 and description do not exist on NT

        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Ejemplo n.º 9
0
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
    # Before doing anything, remove any perfmon counters.
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    # The EXE location may have changed
    exeName = '"%s"' % LocatePythonServiceExe(exeName)

    # Handle the default arguments.
    if startType is None: startType = win32service.SERVICE_NO_CHANGE
    if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    commandLine = _GetCommandLine(exeName, exeArgs)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:

            win32service.ChangeServiceConfig(hs,
                serviceType,  # service type
                startType,
                errorControl,       # error control type
                commandLine,
                None,
                0,
                serviceDeps,
                userName,
                password,
                displayName)
            if description is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
                except NotImplementedError:
                    pass    ## ChangeServiceConfig2 and description do not exist on NT

        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
Ejemplo n.º 10
0
def create(
    name,
    bin_path,
    exe_args=None,
    display_name=None,
    description=None,
    service_type="own",
    start_type="manual",
    start_delayed=False,
    error_control="normal",
    load_order_group=None,
    dependencies=None,
    account_name=".\\LocalSystem",
    account_password=None,
    run_interactive=False,
    **kwargs
):
    """
    Create the named service.

    .. versionadded:: 2015.8.0

    Args:

        name (str):
            Specifies the service name. This is not the display_name

        bin_path (str):
            Specifies the path to the service binary file. Backslashes must be
            escaped, eg: ``C:\\path\\to\\binary.exe``

        exe_args (str):
            Any additional arguments required by the service binary.

        display_name (str):
            The name to be displayed in the service manager. If not passed, the
            ``name`` will be used

        description (str):
            A description of the service

        service_type (str):
            Specifies the service type. Default is ``own``. Valid options are as
            follows:

            - kernel: Driver service
            - filesystem: File system driver service
            - adapter: Adapter driver service (reserved)
            - recognizer: Recognizer driver service (reserved)
            - own (default): Service runs in its own process
            - share: Service shares a process with one or more other services

        start_type (str):
            Specifies the service start type. Valid options are as follows:

            - boot: Device driver that is loaded by the boot loader
            - system: Device driver that is started during kernel initialization
            - auto: Service that automatically starts
            - manual (default): Service must be started manually
            - disabled: Service cannot be started

        start_delayed (bool):
            Set the service to Auto(Delayed Start). Only valid if the start_type
            is set to ``Auto``. If service_type is not passed, but the service
            is already set to ``Auto``, then the flag will be set. Default is
            ``False``

        error_control (str):
            The severity of the error, and action taken, if this service fails
            to start. Valid options are as follows:

            - normal (normal): Error is logged and a message box is displayed
            - severe: Error is logged and computer attempts a restart with the
              last known good configuration
            - critical: Error is logged, computer attempts to restart with the
              last known good configuration, system halts on failure
            - ignore: Error is logged and startup continues, no notification is
              given to the user

        load_order_group (str):
            The name of the load order group to which this service belongs

        dependencies (list):
            A list of services or load ordering groups that must start before
            this service

        account_name (str):
            The name of the account under which the service should run. For
            ``own`` type services this should be in the ``domain\\username``
            format. The following are examples of valid built-in service
            accounts:

            - NT Authority\\LocalService
            - NT Authority\\NetworkService
            - NT Authority\\LocalSystem
            - .\\LocalSystem

        account_password (str):
            The password for the account name specified in ``account_name``. For
            the above built-in accounts, this can be None. Otherwise a password
            must be specified.

        run_interactive (bool):
            If this setting is True, the service will be allowed to interact
            with the user. Not recommended for services that run with elevated
            privileges.

    Returns:
        dict: A dictionary containing information about the new service

    CLI Example:

    .. code-block:: bash

        salt '*' service.create <service name> <path to exe> display_name='<display name>'
    """
    if display_name is None:
        display_name = name

    # Test if the service already exists
    if name in get_all():
        raise CommandExecutionError("Service Already Exists: {}".format(name))

    # shlex.quote the path to the binary
    bin_path = _cmd_quote(bin_path)
    if exe_args is not None:
        bin_path = "{} {}".format(bin_path, exe_args)

    if service_type.lower() in SERVICE_TYPE:
        service_type = SERVICE_TYPE[service_type.lower()]
        if run_interactive:
            service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS
    else:
        raise CommandExecutionError("Invalid Service Type: {}".format(service_type))

    if start_type.lower() in SERVICE_START_TYPE:
        start_type = SERVICE_START_TYPE[start_type.lower()]
    else:
        raise CommandExecutionError("Invalid Start Type: {}".format(start_type))

    if error_control.lower() in SERVICE_ERROR_CONTROL:
        error_control = SERVICE_ERROR_CONTROL[error_control.lower()]
    else:
        raise CommandExecutionError("Invalid Error Control: {}".format(error_control))

    if start_delayed:
        if start_type != 2:
            raise CommandExecutionError(
                'Invalid Parameter: start_delayed requires start_type "auto"'
            )

    if account_name in [
        "LocalSystem",
        ".\\LocalSystem",
        "LocalService",
        ".\\LocalService",
        "NetworkService",
        ".\\NetworkService",
    ]:
        account_password = ""

    # Connect to Service Control Manager
    handle_scm = win32service.OpenSCManager(
        None, None, win32service.SC_MANAGER_ALL_ACCESS
    )

    # Create the service
    handle_svc = win32service.CreateService(
        handle_scm,
        name,
        display_name,
        win32service.SERVICE_ALL_ACCESS,
        service_type,
        start_type,
        error_control,
        bin_path,
        load_order_group,
        0,
        dependencies,
        account_name,
        account_password,
    )

    if description is not None:
        win32service.ChangeServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description
        )

    if start_delayed is not None:
        # You can only set delayed start for services that are set to auto start
        # Start type 2 is Auto
        if start_type == 2:
            win32service.ChangeServiceConfig2(
                handle_svc,
                win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                start_delayed,
            )

    win32service.CloseServiceHandle(handle_scm)
    win32service.CloseServiceHandle(handle_svc)

    return info(name)
Ejemplo n.º 11
0
def modify(
    name,
    bin_path=None,
    exe_args=None,
    display_name=None,
    description=None,
    service_type=None,
    start_type=None,
    start_delayed=None,
    error_control=None,
    load_order_group=None,
    dependencies=None,
    account_name=None,
    account_password=None,
    run_interactive=None,
):
    # pylint: disable=anomalous-backslash-in-string
    """
    Modify a service's parameters. Changes will not be made for parameters that
    are not passed.

    .. versionadded:: 2016.11.0

    Args:
        name (str):
            The name of the service. Can be found using the
            ``service.get_service_name`` function

        bin_path (str):
            The path to the service executable. Backslashes must be escaped, eg:
            ``C:\\path\\to\\binary.exe``

        exe_args (str):
            Any arguments required by the service executable

        display_name (str):
            The name to display in the service manager

        description (str):
            The description to display for the service

        service_type (str):
            Specifies the service type. Default is ``own``. Valid options are as
            follows:

            - kernel: Driver service
            - filesystem: File system driver service
            - adapter: Adapter driver service (reserved)
            - recognizer: Recognizer driver service (reserved)
            - own (default): Service runs in its own process
            - share: Service shares a process with one or more other services

        start_type (str):
            Specifies the service start type. Valid options are as follows:

            - boot: Device driver that is loaded by the boot loader
            - system: Device driver that is started during kernel initialization
            - auto: Service that automatically starts
            - manual: Service must be started manually
            - disabled: Service cannot be started

        start_delayed (bool):
            Set the service to Auto(Delayed Start). Only valid if the start_type
            is set to ``Auto``. If service_type is not passed, but the service
            is already set to ``Auto``, then the flag will be set.

        error_control (str):
            The severity of the error, and action taken, if this service fails
            to start. Valid options are as follows:

            - normal: Error is logged and a message box is displayed
            - severe: Error is logged and computer attempts a restart with the
              last known good configuration
            - critical: Error is logged, computer attempts to restart with the
              last known good configuration, system halts on failure
            - ignore: Error is logged and startup continues, no notification is
              given to the user

        load_order_group (str):
            The name of the load order group to which this service belongs

        dependencies (list):
            A list of services or load ordering groups that must start before
            this service

        account_name (str):
            The name of the account under which the service should run. For
            ``own`` type services this should be in the ``domain\\username``
            format. The following are examples of valid built-in service
            accounts:

            - NT Authority\\LocalService
            - NT Authority\\NetworkService
            - NT Authority\\LocalSystem
            - .\\LocalSystem

        account_password (str):
            The password for the account name specified in ``account_name``. For
            the above built-in accounts, this can be None. Otherwise a password
            must be specified.

        run_interactive (bool):
            If this setting is True, the service will be allowed to interact
            with the user. Not recommended for services that run with elevated
            privileges.

    Returns:
        dict: a dictionary of changes made

    CLI Example:

    .. code-block:: bash

        salt '*' service.modify spooler start_type=disabled

    """
    # pylint: enable=anomalous-backslash-in-string
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx
    handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm,
            name,
            win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG,
        )
    except pywintypes.error as exc:
        raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror))

    config_info = win32service.QueryServiceConfig(handle_svc)

    changes = dict()

    # Input Validation
    if bin_path is not None:
        # shlex.quote the path to the binary
        bin_path = _cmd_quote(bin_path)
        if exe_args is not None:
            bin_path = "{} {}".format(bin_path, exe_args)
        changes["BinaryPath"] = bin_path

    if service_type is not None:
        if service_type.lower() in SERVICE_TYPE:
            service_type = SERVICE_TYPE[service_type.lower()]
            if run_interactive:
                service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS
        else:
            raise CommandExecutionError("Invalid Service Type: {}".format(service_type))
    else:
        if run_interactive is True:
            service_type = config_info[0] | win32service.SERVICE_INTERACTIVE_PROCESS
        elif run_interactive is False:
            service_type = config_info[0] ^ win32service.SERVICE_INTERACTIVE_PROCESS
        else:
            service_type = win32service.SERVICE_NO_CHANGE

    if service_type is not win32service.SERVICE_NO_CHANGE:
        flags = list()
        for bit in SERVICE_TYPE:
            if isinstance(bit, int) and service_type & bit:
                flags.append(SERVICE_TYPE[bit])

        changes["ServiceType"] = flags if flags else service_type

    if start_type is not None:
        if start_type.lower() in SERVICE_START_TYPE:
            start_type = SERVICE_START_TYPE[start_type.lower()]
        else:
            raise CommandExecutionError("Invalid Start Type: {}".format(start_type))
        changes["StartType"] = SERVICE_START_TYPE[start_type]
    else:
        start_type = win32service.SERVICE_NO_CHANGE

    if error_control is not None:
        if error_control.lower() in SERVICE_ERROR_CONTROL:
            error_control = SERVICE_ERROR_CONTROL[error_control.lower()]
        else:
            raise CommandExecutionError(
                "Invalid Error Control: {}".format(error_control)
            )
        changes["ErrorControl"] = SERVICE_ERROR_CONTROL[error_control]
    else:
        error_control = win32service.SERVICE_NO_CHANGE

    if account_name is not None:
        changes["ServiceAccount"] = account_name
    if account_name in ["LocalSystem", "LocalService", "NetworkService"]:
        account_password = ""

    if account_password is not None:
        changes["ServiceAccountPassword"] = "******"

    if load_order_group is not None:
        changes["LoadOrderGroup"] = load_order_group

    if dependencies is not None:
        changes["Dependencies"] = dependencies

    if display_name is not None:
        changes["DisplayName"] = display_name

    win32service.ChangeServiceConfig(
        handle_svc,
        service_type,
        start_type,
        error_control,
        bin_path,
        load_order_group,
        0,
        dependencies,
        account_name,
        account_password,
        display_name,
    )

    if description is not None:
        win32service.ChangeServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description
        )
        changes["Description"] = description

    if start_delayed is not None:
        # You can only set delayed start for services that are set to auto start
        # Start type 2 is Auto
        # Start type -1 is no change
        if (start_type == -1 and config_info[1] == 2) or start_type == 2:
            win32service.ChangeServiceConfig2(
                handle_svc,
                win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                start_delayed,
            )
            changes["StartTypeDelayed"] = start_delayed
        else:
            changes["Warning"] = 'start_delayed: Requires start_type "auto"'

    win32service.CloseServiceHandle(handle_scm)
    win32service.CloseServiceHandle(handle_svc)

    return changes
Ejemplo n.º 12
0
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals

import win32service
import win32serviceutil

svc_name = "UDSActor"

try:
    hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)

    try:
        hs = win32serviceutil.SmartOpenService(hscm, svc_name, win32service.SERVICE_ALL_ACCESS)
        service_failure_actions = {
            'ResetPeriod': 864000,  # Time in ms after which to reset the failure count to zero.
            'RebootMsg': u'',  # Not using reboot option
            'Command': u'',  # Not using run-command option
            'Actions': [
                (win32service.SC_ACTION_RESTART, 5000),  # action, delay in ms
                (win32service.SC_ACTION_RESTART, 5000)
            ]
        }
        win32service.ChangeServiceConfig2(hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions)
    finally:
        win32service.CloseServiceHandle(hs)
finally:
    win32service.CloseServiceHandle(hscm)